7

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?

potashin
  • 44,205
  • 11
  • 83
  • 107
Alek
  • 1,461
  • 2
  • 13
  • 14

1 Answers1

10

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? }
potashin
  • 44,205
  • 11
  • 83
  • 107