(Ruby on Rails validates_confirmation_of) How to switch error message to the confirmation field?

41 Views Asked by At

In Ruby on Rails 3.2, I am trying to validate password confirmation with this:

validates_confirmation_of :password

Rails will add the validation error to the :password field. How do I make the validation error be added to the :password_confirmation field instead?

1

There are 1 best solutions below

2
smathy On

Which version of Rails are you using? It should add the error to the :password_confirmation attribute:

[9] pry(main)> class Foo < ApplicationRecord; attribute :password; validates_confirmation_of :password; end
=> [ActiveModel::Validations::ConfirmationValidator]
[10] pry(main)> ff = Foo.new(password: "foo", password_confirmation: "bar"); ff.validate
=> false
[11] pry(main)> ff.errors
=> #<ActiveModel::Errors [#<ActiveModel::Error attribute=password_confirmation, type=confirmation, options={:attribute=>"Password"}>]>
[12] pry(main)> ff.errors[:password_confirmation]
=> ["doesn't match Password"]

Plot Twist: OP reveals it's Rails 3.2

I'd probably add (something like) this in my controller:

if @model.errors.added? :password, :confirmation
  @model.errors.add :password_confirmation, :confirmation
  @model.errors.delete :password, :confirmation
end