我正在使用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"
相关字段时,并未显示错误。上面写正则表达式的正确方法是什么?
答案 0 :(得分:1)
First and Foremost新方法不会触发对象的任何类型的验证。
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_of 和 validates_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"})
有关详细信息,您可以从这些验证助手中获取帮助=&gt; http://api.rubyonrails.org/classes/ActiveModel/Validations/HelperMethods.html
答案 1 :(得分:0)
尝试这样的事情
validates :email, presence: true, format: { with: /\A([^\}\{\]\[@\s\,]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i }