Permalink
Browse files

allow multiple regexp with their own error message

  • Loading branch information...
1 parent 4c2c4a0 commit 25110f722453c11b11cfd13bf7c22d8f7721b60d @sbounmy committed Feb 10, 2014
Showing with 26 additions and 3 deletions.
  1. +9 −0 lib/devise_security_extension.rb
  2. +17 −3 lib/devise_security_extension/models/secure_validatable.rb
@@ -12,6 +12,15 @@ module Devise
@@expire_password_after = 3.months
# Validate password for strongness
+ # Allow to validate single regex as :
+ # config.password_regex = /[a-z]/
+ # I18n error message : active_record.messages.password_length
+ #
+ # or with multiple regexp and its name (useful for error message)
+ #
+ # config.password_regex = { should_have_mixed_case_letters: /(?=.*[a-z])(?=.*[A-Z])/, should_have_digits: /(?=.*\d)/ }
+ # I18n error message : active_record.messages.should_have_mixed_case_letters, active_record.messages.should_have_digits
+ #
mattr_accessor :password_regex
@@password_regex = /(?=.*\d)(?=.*[a-z])(?=.*[A-Z])/
@@ -61,9 +61,23 @@ def current_equal_password_validation
protected
- # validates :password, :format => { :with => password_regex, :message => :password_format }
+ # Allow to validate single regex as :
+ # config.password_regex = /[a-z]/
+ # I18n error message : active_record.messages.password_length
+ #
+ # or with multiple regexp and its regexp name (useful for error message)
+ #
+ # config.password_regex = { should_have_mixed_case_letters: /(?=.*[a-z])(?=.*[A-Z])/, should_have_digits: /(?=.*\d)/ }
+ # I18n error message : active_record.messages.should_have_mixed_case_letters, active_record.messages.should_have_digits
+ #
def password_format_should_be_valid
- errors.add(:password, :password_format) unless password =~ self.class.password_regex
+ if (regex = self.class.password_regex).is_a? Regexp
+ errors.add(:password, :password_format) unless password =~ regex
+ else
+ regex.each do |name, exp|
+ errors.add(:password, name.to_sym) unless password =~ exp
+ end
+ end
end
# Checks whether a password is needed or not. For validations only.
@@ -83,7 +97,7 @@ module ClassMethods
private
def has_uniqueness_validation_of_login?
validators.any? do |validator|
- validator.class.name =~ /::Validations::UniquenessValidator$/) &&
+ validator.class.name =~ /::Validations::UniquenessValidator$/ &&
validator.attributes.include?(login_attribute)
end
end

0 comments on commit 25110f7

Please sign in to comment.