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?
Asked
Active
Viewed 4,471 times
7
-
What is your Rails version? – potashin Apr 26 '15 at 16:02
-
4.2.0, why do you ask? – Alek Apr 26 '15 at 16:08
-
example with `unless:` has a different syntax in Rails version < 4 – potashin Apr 26 '15 at 16:10
1 Answers
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