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?
Validate attribute's length if present
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? }
© 2022 - 2024 — McMap. All rights reserved.
unless:
has a different syntax in Rails version < 4 – Wifely