0

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?

0

    1 Answer 1

    0

    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 
    2
    • I'm using Rails 3.2. Your answer is correct for Rails 4 and above, but I need it to work for earlier versions.CommentedJun 30, 2023 at 15:18
    • @Starscream512 That is 10 years old. I'm guessing upgrading is out of the question?
      – Schwern
      CommentedJun 30, 2023 at 15:23

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.