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

后端 未结 9 1830
清歌不尽
清歌不尽 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:07

    I think it might need something like:

    validates_length_of :foo, minimum: 5, maximum: 5, allow_blank: true
    

    More examples: ActiveRecord::Validations::ClassMethods

    0 讨论(0)
  • 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?}
    
    0 讨论(0)
  • 2021-01-30 20:11

    Add in your model:

    validates :color, length: { is: 7 }
    

    color is a string:

    t.string :color, null: false, default: '#0093FF', limit: 7
    
    0 讨论(0)
提交回复
热议问题