Class: ActiveModel::Validations::PasswordValidator

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
lib/password_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object

Using multiple validators for passwords sucks because either the user receives a flood of (often redundant) errors, or each validation must become conditional, which can get complex fairly quickly.

This class attempts to perform validations in a specific order of importance and only displays the errors that are relevant.

todo: add tests todo: add more options todo: check for password strength todo: use I18n for errors



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/password_validator.rb', line 17

def validate(record)
  @password = record.try(:password)
  @password_confirmation = record.try(:password_confirmation)

  case
  when blank?
    record.errors.add(:password, "can't be blank") unless record.persisted?
  when too_short?
    record.errors.add(:password, "must be a minimum of #{options[:min_length]} characters in length")
  when too_common?
    record.errors.add(:password, "is too common")
  when not_confirmed?
    record.errors.add(:password_confirmation, "doesn't match password")
  end
end