Question

I have a password field and that validates presence and length and both are working fine. But when I submit the form with blank password field, it displays error messages for both validations.

What I want is if the password is blank then length validator must not checked and display error message for only presence validator. Length validator will only be checked if password is present.

Was it helpful?

Solution 2

Along with other validations pass this

:allow_blank => true

For example

validates :password, :presence => true, :length => { :maximum => 20, :allow_blank => true }

OTHER TIPS

You can use Object#with_options and ActiveRecord::Base#new_record?:

class User < ActiveRecord::Base
  with_options :if => :new_record? do |user|
    user.validates :password, presence: true, length: { maximum: 20 }
  end
end  

Look rails conditional validation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top