Devise password confirmation

abuisman edited this page Mar 22, 2012 · 2 revisions

Devise password confirmation

When using Devise you might notice that if you are editing a user's password the client side validation isn't working for the confirmation field, but only is when creating a new user.

The expected behaviour is that any form with :password_confirmation in it shows an error when the two password fields don't match up. This only works in the registration form of Devise however, even when you add :validate => true to the field. (Which you should have done either way, otherwise this solution won't work either).

This is because, by default, Devise only adds the validates_confirmation_of :password on the 'User' model (or any other model you chose as the authentication model) in the case of a :create. When updating we are of course editing rather than creating.

This looks as follows in Devise's source:

validates_confirmation_of :password, :only => :create

To fix this inconvenience you will have to add the following line to your User model (again; or other model you chose):

validates_confirmation_of :password

Here is an example of what that could look like:

class User < ActiveRecord::Base
   # Include default devise modules. Others available are:
   # :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
   devise :database_authenticatable, :registerable,
    :recoverable, :rememberable, :trackable, :validatable, :token_authenticatable, :confirmable, :lockable

   # Setup accessible (or protected) attributes for your model
   attr_accessible :first_name, :last_name, :email, :password, :password_confirmation, :remember_me

   validates_confirmation_of :password

end

Make sure to put the line at the end in order for it not to be overridden by any of Devise's own settings.

Note: Now your user confirmation will be checked every time you set User.password_confirmation.