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
ruby-on-rails activerecord ruby-on-rails-4 ruby-on-rails-4.2 rails-activerecord


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


source to share







All Articles
Loading...
X
Show
Funny
Dev
Pics