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.

有帮助吗?

解决方案 2

Along with other validations pass this

:allow_blank => true

For example

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top