如何在 Rails 模型验证中编写正则表达式?

戴夫

我正在使用 Rails 5。如果我的模型中的一个属性仅由字母组成或者它"\d:\d"在其值的任何位置包含模式我希望它的一个属性无法通过验证我试过这个

  validates_format_of :my_attr, numericality: { greater_than: 0, :only_integer => true }, :allow_blank => true, :without => /(\d:\d|^\p{L}+$)/

但是当我创建一个新对象时

2.4.0 :018 > ab = MyObjectTime.new({:my_attr => "ab"})

当我查询"ab.errors"相关字段时,它并不表示错误上面正则表达式的正确写法是什么?

内哈·乔普拉

首先,新方法不会在对象上触发任何类型的验证。

class Person < ApplicationRecord
  validates :name, presence: true
end

>> p = Person.new
# => #<Person id: nil, name: nil>
>> p.errors.messages
# => {}

new method does not trigger any validation on an object as it is not hitting the database to save the record. 
>> p.save
# => false

save method will try to create the record to the database and triggers the respective validation on the object.


>> p.valid?
# => false

When you hit the .valid? the method, it validates the object against the mentioned validation.

>> p.errors.messages
# => {name:["can't be blank"]}

>> p = Person.create
# => #<Person id: nil, name: nil>

Creating and saving a new record will send an SQL INSERT operation to the database.

Internal functionality of Person.create is Person.new and Person.save

When you are creating an object, it tries to create the valid record to the database and triggers the respective validation.

>> p.errors.messages
# => {name:["can't be blank"]}

>> p.save
# => false

>> p.save!
# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

>> Person.create!
# => ActiveRecord::RecordInvalid: Validation failed: Name can't be blank

其次,validates_numericality_ofvalidates_format_of是您混合使用的不同验证助手集。

  validates_numericality_of :my_attr, :only_integer => true, :allow_blank => true,
                            :greater_than => 0

validates_format_of :my_attr, :without => /(\d:\d|^\p{L}+$)/

This validation won't accept any such object :
MyObjectTime.new({:my_attr => "ab"})
MyObjectTime.new({:my_attr => "1:1"})

有关更多信息,您可以从这些验证助手中获取帮助 => http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在Rails模型中编写正则表达式查询

Ruby on Rails 3.2.17 | 我如何为英国货币编写正则表达式

如何在XSD中编写正则表达式

如何在正则表达式中验证BIGINT

Rails中的正则表达式验证

如何在匹配表达式中编写正则表达式文字?

如何在前端的Rails后端中使用正则表达式?

如何在 Firestore 安全规则中正确编写正则表达式验证

如何编写正则表达式

如何验证正则表达式

如何从我的函数中编写正则表达式模式以验证自定义电话号码?

如何在Lucene中编写正则表达式模式?

如何在python中编写更好的正则表达式?

如何在ColdFusion中编写此正则表达式?

如何在Java中编写和使用正则表达式

如何在[]中编写行首“ ^”和行尾“ $”的正则表达式?

如何在Java中为unicode名正确编写正则表达式?

如何在/ bin / sh脚本中编写和匹配正则表达式?

如何在Golang中编写简单的正则表达式?

如何在目标C(NSRegularExpression)中编写正则表达式?

如何在mysql中编写正则表达式前瞻/后视

如何在Scrapy中为XPath编写正则表达式?

如何在POSIX正则表达式中编写负前瞻

如何在JavaScript中编写包含括号的正则表达式?

如何在PySpark中编写条件正则表达式替换?

如何在re_path django 3中正确编写正则表达式

如何在 Kotlin 中正确编写此正则表达式以测试 Pascal 中的代码

如何在R中捆绑编写正则表达式OR语句

如何在较长的段落中为这句话编写正则表达式模式?