Search code examples
ruby-on-rails-3validationpassword-confirmation

Do not show 'New password does not match confirmation' before the user enters input in Rails


I'm trying to "tweak" a behavior that I am seeing using Ruby on Rails validator. In our application, we ask for password confirmation before changing a password.

That is very easy with the Ruby validators, just adding the validation on the model

 class ChangePassword < BaseModel
    validates_confirmation_of :password

That automatically activates JavaScript to check it on the client side, but the problem is that, when the user enters the password and before enters the confirmation password, it launches the 'New password doesn't match confirmation'.

I need to change that behavior so it doesn't show that on the JavaScript side if the confirmation password is empty, but keeps raising that error if the user hits the "Send form" button.

Is this possible in Rails?

Thank you


Solution

  • You can do that by conditional validation technique.

    class ChangePassword < BaseModel
      validates_confirmation_of :password, :if => :password_present?
    
       private
       def password_present?
         password.present?
       end
    end