Skip to content

Instantly share code, notes, and snippets.

@bcardarella
Created November 25, 2012 02:22
Show Gist options
  • Save bcardarella/4142149 to your computer and use it in GitHub Desktop.
Save bcardarella/4142149 to your computer and use it in GitHub Desktop.
Proper password confirmation
en:
errors:
messages:
confirmation: "doesn't match %{attribute}"
class User < ActiveRecord::Base
class ConfirmationValidator < ActiveModel::EachValidator # :nodoc:
def initialize(options)
options[:attributes] = options[:attributes].map { |attribute| "#{attribute}_confirmation" }
super
end
def validate_each(record, attribute, value)
attribute_to_confirm = attribute.to_s.sub('_confirmation', '')
confirmed = record.send(attribute_to_confirm)
if value != confirmed
human_attribute_name = record.class.human_attribute_name(attribute_to_confirm)
record.errors.add(attribute, :confirmation, options.merge(:attribute => human_attribute_name))
end
end
def client_side_hash(model, attribute, force = nil)
attribute_to_confirm = attribute.to_s.split(/_confirmation/)[0]
human_attribute_name = model.class.human_attribute_name(attribute_to_confirm)
build_client_side_hash(model, attribute, self.options.dup.merge(:attribute => human_attribute_name))
end
def setup(klass)
klass.send(:attr_accessor, *attributes.map do |attribute|
attribute unless klass.method_defined?(attribute)
end.compact)
end
end
validates :password, :confirmation => true
end
@jerryshen
Copy link

Hi, it seems not work for me.
I'm using devise, and I followed your gist,

add

  = f.input :password, required: true, validate: { confirmation: true }
  = f.input :password_confirmation

the the confirmation validation was still fired on the password field

any ideas?

@nitinsinghit
Copy link

Did you find a solution for it??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment