我有一个领域,我想验证。我希望字段能够留空,但是如果用户输入数据,我希望它是某种格式的。目前我在模型中使用下面的验证,但是这不允许用户将其留空:
validates_length_of :foo, :maximum => 5 validates_length_of :foo, :minimum => 5
我如何写这个来完成我的目标?
From the validates_length_of documentation:
validates_length_of :phone, :in => 7..32, :allow_blank => true
:allow_blank - Attribute may be blank; skip validation.
:allow_blank
I think it might need something like:
validates_length_of :foo, minimum: 5, maximum: 5, allow_blank: true
More examples: ActiveRecord::Validations::ClassMethods
In your model e.g.
def validate errors.add_to_base 'error message' unless self.foo.length == 5 or self.foo.blanc? end
every validates_* accepts :if or :unless options
validates_length_of :foo, :maximum => 5, :if => :validate_foo_condition
where validate_foo_condition is method that returns true or false
you can also pass a Proc object:
validates_length_of :foo, :maximum => 5, :unless => Proc.new {|object| object.foo.blank?}
You can also use this format:
validates :foo, length: {minimum: 5, maximum: 5}, allow_blank: true
Or since your min and max are the same, the following will also work:
validates :foo, length: {is: 5}, allow_blank: true
Or even more concise (with the new hash syntax), from the validates documentation:
validates :foo, length: 5..5, allow_blank: true
The upper limit should probably represent somehting more meaningful like "in: 5..20", but just answering the question to the letter.
validates_length_of :reason, minimum: 3, maximum: 30
rspec for the same is
it { should validate_length_of(:reason).is_at_least(3).is_at_most(30) }
How about that: validates_length_of :foo, is: 3, allow_blank: true
validates_length_of :foo, is: 3, allow_blank: true
Add in your model:
validates :color, length: { is: 7 }
color is a string:
t.string :color, null: false, default: '#0093FF', limit: 7