Validate attribute's length if present
Asked Answered
L

1

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?

Listed answered 26/4, 2015 at 15:48 Comment(3)
What is your Rails version?Wifely
4.2.0, why do you ask?Listed
example with unless: has a different syntax in Rails version < 4Wifely
W
11

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? }
Wifely answered 26/4, 2015 at 15:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.