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

后端 未结 9 1817
清歌不尽
清歌不尽 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 19:46

    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
    
    0 讨论(0)
  • 2021-01-30 19:49
    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) }
    
    0 讨论(0)
  • 2021-01-30 19:56

    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.

    0 讨论(0)
  • 2021-01-30 20:01

    From the validates_length_of documentation:

    validates_length_of :phone, :in => 7..32, :allow_blank => true
    

    :allow_blank - Attribute may be blank; skip validation.

    0 讨论(0)
  • 2021-01-30 20:03

    How about that: validates_length_of :foo, is: 3, allow_blank: true

    0 讨论(0)
  • 2021-01-30 20:04

    In your model e.g.

    def validate
      errors.add_to_base 'error message' unless self.foo.length == 5 or self.foo.blanc?
    end
    
    0 讨论(0)
提交回复
热议问题