Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is validates_presence_of necessary if using validates_length_of?

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?

like image 221
mlambie Avatar asked Dec 30 '22 13:12

mlambie


1 Answers

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.

like image 62
EmFi Avatar answered Jan 13 '23 16:01

EmFi