Cory L
Cory L

Reputation: 273

Rails password_confirmation not working

I need help getting my user signup form to validate that password and password_confirmation match exactly.

Currently the form will pass the data entered into the password digest field in the database and will accept any input in the password_confirmation field, and will not give any errors.

My code is as follows;

Model - user.rb

class User < ApplicationRecord

    before_save { self.email = email.downcase }
    #attr_accessible :user_name, :email
    validates_confirmation_of :password
    has_secure_password

    validates :user_name, presence: true, length: { maximum: 25 }
    VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
    validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }
    validates :password, presence: true, confirmation: true, length: { minimum: 6 }

    has_many :trips
    has_many :countries, through: :trips

end

view - new.html.erb

<div class="container">
  <h1 class="text-center" style="margin-top: 10px;" >Sign up</h1>
  <div class="row">
    <div class="col-md-6 offset-md-3 ">
      <%=form_for(@user) do |f| %>
      <%= render 'shared/error_messages' %>
      <div class="form-group">
        <%= f.label :user_name, "Username" %>
        <%= f.text_field :user_name, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.label :email %>
        <%= f.email_field :email, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.label :password %>
        <%= f.password_field :password, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.label :password_confirmation, "Password Confirmation" %>
        <%= f.password_field :password_confirmation, class: "form-control" %>
      </div>

      <div class="form-group">
        <%= f.submit "Create an account", class: 'form-control btn btn-primary' %>
      </div>
      <% end %> 
    </div>
  </div>
</div>

I also have bcrypt -v 3.1.7 in my gemfile. If any other info is needed let me know and I am happy to provide.

Upvotes: 1

Views: 1744

Answers (1)

CV-Gate
CV-Gate

Reputation: 1170

I think that you are not getting the password_confirmation, to do that you should add

validates :password_confirmation, presence: true

Also, in your controller, you should whitelist :password_confirmation into your permit section.

Validates confirmation only validates if password_confirmation is not nil.

Upvotes: 4

Related Questions