Validators, password confirmation
Asked Answered
S

2

18

I can't figure out why the model doesen't check for the password confirmation, this is the code of the model:

class User < ActiveRecord::Base
  attr_accessor :password_confirmation
  validates :email, :presence =>true,
                    :uniqueness=>true
  validates :password, :presence =>true,
                    :length => { :minimum => 5, :maximum => 40 },
                    :confirmation =>true
  validates_confirmation_of :password
end

The controller is intended take the data from the view and try to perform a save, this is the code of the view:

<h1>Registration process</h1>
<%= form_for(@new_user) do |f|%>
<% if @new_user.errors.any? %>
  <div id="errorExplanation">
    <h2><%= pluralize(@new_user.errors.count, "error") %> prohibited this article from being saved:</h2>
    <ul>
    <% @new_user.errors.full_messages.each do |msg| %>
      <li><%= msg %></li>
    <% end %>
    </ul>
  </div>
  <% end %>
    <%= f.label :email %><br />
    <%= f.text_field :email %><br />
    <%= f.label :password %><br />
    <%= f.password_field :password %><br />
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation %>
    <%#TODO Confirm password%>

    <%= f.submit 'Join' %>
<%end%>

No errors come out if the password doesn't match.

Simplistic answered 15/1, 2011 at 1:29 Comment(2)
Do you need the double confirmation validation? You specify :confirmation => true in the password's validation.Rothrock
Yeah...the code works for me too (as Chamnap said) and having a double password_confirmation validator shouldn't be the reason for it not to work., it just would give you twice a message "Password doesn't match confirmation"Tablecloth
C
36

I just got burned by this one too. I suspect your confirmation value is nil. From the docs:

NOTE: This check is performed only if password_confirmation is not nil, and by default only on save. To require confirmation, make sure to add a presence check for the confirmation attribute:

Also, you don't need attr_accessor :password_confirmation, since the validation adds it for you. Rails!

Catawba answered 5/5, 2011 at 2:23 Comment(2)
Thanks - this was giving me some heartburn as well!Catha
how can i make the confirmation NOT nil?Proportionate
S
1

If you are using a mass assignment than you need to add password to attr_accessible. attr_accessor will create a virtual attribute but the same will not be available for mass assignment Idealy we should not be adding password_confirmation to the attr_accessible, validates_confirmation_of should validate the value of password and password_confirmation but the value of password_confirmation is coming nill. I added password_confirmation to attr_accessible and it works properly

Working with Rails 3.

Spinner answered 7/6, 2012 at 8:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.