Rails: Validating min and max length of a string but allowing it to be blank

后端 未结 9 1816
清歌不尽
清歌不尽 2021-01-30 19:14

I have a field that I would like to validate. I want the field to be able to be left blank, but if a user is entering data I want it to be in a certain format. Currently I am us

9条回答
  •  囚心锁ツ
    2021-01-30 20:08

    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?}
    

提交回复
热议问题