ruby-on-railsruby-on-rails-4activerecordrails-activerecordruby-on-rails-4.2

Validate attribute's length if present


How to make validation where presence of model's attribute isn't necessary, but if it is present, attribute's length must be more than three characters?


Solution

  • You can allow attribute to be blank with allow_blank: true or nil with allow_nil: true and also check the length: :

    validates :attr, length: { minimum: 4 }, allow_blank: true
    validates :attr, length: { minimum: 4 }, allow_nil: true
    

    You can also use if: or unless: :

    validates :attr, length: {minimum: 4}, unless: -> (item) { item.blank? }