Devise: Disable password confirmation during sign-up

后端 未结 9 990
走了就别回头了
走了就别回头了 2020-12-24 01:13

I am using Devise for Rails. In the default registration process, Devise requires users to type the password twice for validation and authentication. How can I disable it?

9条回答
  •  -上瘾入骨i
    2020-12-24 01:51

    To disable password confirmation you can simply remove the password_confirmation field from the registration form. This disables the need to confirm the password entirely!

    1. Generate devise views if you haven't: rails g devise:views
    2. Remove the password_confirmation section in app\views\devise\registrations\new.html.erb

    One way to do it:

    <%# Disable password confirmation so that the user doesn't have to enter a password twice %>
    <% if false %>
      
    <%= f.label :password_confirmation %>
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
    <% end %>

    The reason why this works lies in lib/devise/models/validatable.rb in the Devise source:

    module Devise
      module Models
        module Validatable
    
    
          def self.included(base)
    
            base.class_eval do
              #....SNIP...
              validates_confirmation_of :password, :if => :password_required?
            end
          end
    
          #...SNIP...
    
          def password_required?
            !persisted? || !password.nil? || !password_confirmation.nil?
          end
        end
      end
    end
    

    Note that the validation is only triggered if password_required? returns true, and password_required? will return false if the password_confirmation field is nil.

    Because where the password_confirmation field is present in the form, it will always be included in the parameters hash , as an empty string if it is left blank, the validation is triggered. However, if you remove the input from the form, the password_confirmation in the params will be nil, and therefore the validation will not be triggered.

提交回复
热议问题