Class: PasswordValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/password_validation/validators.rb

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attr, password) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/password_validation/validators.rb', line 2

def validate_each(record, attr, password)
  opts = {
    length: {minimum: 8, message: ->(opts, _) { "must be at least #{opts[:minimum]} characters" }},
    uppercase: {required: true, message: 'must include an uppercase letter (A-Z)'},
    lowercase: {required: true, message: 'must include a lowercase letter (a-z)'},
    numeral: {required: true, message: 'must include a number (0-9)'},
    special: {required: true, pattern: /[`~!@#$%\^&*()\-_=+\[\]{}\\|;:'",.<>\/?]/, message: ->(opts, _) {
      list = opts[:pattern].source[1..-2].gsub('\\', '')
      if opts[:pattern].source.include?('\\\\')
        list << '\\'
      end
      "must include one of these special characters: #{list}"
    }}
  }.deep_merge(options)
  
  errors = record.errors[attr]
  if password
    maybe_validate_length    password, errors, opts
    maybe_validate_lowercase password, errors, opts
    maybe_validate_uppercase password, errors, opts
    maybe_validate_numeral   password, errors, opts
    maybe_validate_special   password, errors, opts
  end
end