In an ActiveRecord model is it considered best practice/necessary to use validates_presence_of
when also using validates_length_of
?
For example:
class Company < ActiveRecord::Base
validates_presence_of :name
validates_length_of :name, :in => 5..30
end
To me, it seems redundant. Having a length between 5 and 30 means that the attribute is also present, yet I see this used everywhere. It also means users get two error messages regarding the same missing attribute, when really only one is needed.
Am I missing something, or are people being overly-zealous when validating data?
validates_presence_of is entirely redundant when used with validates_length_of, except in cases where you supply :allow_nil => true
or :allow_blank => true
to validates_length_of.
Default values for the allow_nil and allow_blank options in any validation is false. validates_presence_of only fails if the attribute is neither nil, or blank. Therefore validates_presence_of is made redundant by most of the supplied validations when neither allow_nil or allow_blank is supplied as options to the validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With