0

How to validate password with confirm password in rails 3.2

my code not work

you can tell where my error

I've tried many variations changing the code in the controller.

Password saves but not validated to the password confirm field and password field.

help me please, help me )))

views

<%= form_for :password, :url => { :action => "change_password" }, :id => @user do |f| %> 
<% if @user.errors.any? %>
    <div class="error_messages">
      <h2>Form is invalid</h2>
      <ul>
        <% for message in @user.errors.full_messages %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
<%= f.password_field :password %>
<%= f.password_field :password_confirmation %>
<%= f.submit "Save", :class => "button blue" %>
<% end %> 

User Controller

  def change_password
    @page_title = "Changing Zetfon account password"
    @user = current_user
    if request.post?

       @user.password = Digest::SHA1.hexdigest(params[:password][:password]) 
    if @user.save
        redirect_to :action => 'profile'
        flash[:status] = "Your password was changed. Next time you sign in use your new password."
      else
     flash[:status] = _('Your password not changed')
        render :action => "change_password"
      end
    end
  end

User Model

  validates_confirmation_of :password
  attr_accessible :password_confirmation
  attr_accessor :password

2 Answers 2

11

add the following line to your model

    validates :password, confirmation: true
Sign up to request clarification or add additional context in comments.

Comments

3

Is it too late to simply use has_secure_password? You can learn about it in this RailsCast:

http://railscasts.com/episodes/270-authentication-in-rails-3-1

I'm not sure why you have if request.post?. Isn't that already determined by your route?

According to the documentation for validates_confirmation_of, I think you might need to add:

validates_presence_of :password_confirmation, :if => :password_changed?

Here's the documentation:

http://apidock.com/rails/ActiveModel/Validations/HelperMethods/validates_confirmation_of

The documentation seems to indicate that you don't need attr_accessible :password_confirmation either.

I hope that helps.

1 Comment

Oh thank you Geoff, that answered, I will check what is wrong

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.