email_address_validator.rb 695 B

123456789101112131415161718
  1. # frozen_string_literal: true
  2. # NOTE: I initially wrote this as `EmailValidator` but it ended up clashing
  3. # with an indirect dependency of ours, `validate_email`, which, turns out,
  4. # has the same approach as we do, but with an extra check disallowing
  5. # single-label domains. Decided to not switch to `validate_email` because
  6. # we do want to allow at least `localhost`.
  7. class EmailAddressValidator < ActiveModel::EachValidator
  8. def validate_each(record, attribute, value)
  9. value = value.strip
  10. address = Mail::Address.new(value)
  11. record.errors.add(attribute, :invalid) if address.address != value
  12. rescue Mail::Field::FieldError
  13. record.errors.add(attribute, :invalid)
  14. end
  15. end