Check the length of an attribute if present
How do I validate when the presence of a model attribute is optional, but if present, the length of the attribute must be more than three characters?
+3
Alek
source
to share
1 answer
You can allow the attribute to be empty with allow_blank: true
or nil
with allow_nil: true
, and also check 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: -> (o) do o.blank? end
+5
potashin
source
to share