Class: EmailDomainChecker::DomainCheckValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/email_domain_checker/active_model_validator.rb

Overview

ActiveModel validator for email domain checking

Usage:

class User < ActiveRecord::Base
  validates :email, domain_check: { check_mx: true, timeout: 3 }, normalize: true
end

Options:

- domain_check: Hash of options for domain validation
  * check_mx: Boolean (default: true) - Check MX records
  * check_a: Boolean (default: false) - Check A records
  * timeout: Integer (default: 5) - DNS query timeout in seconds
  * validate_format: Boolean (default: true) - Validate email format
  * validate_domain: Boolean (default: true) - Validate domain
- normalize: Boolean (default: false) - Normalize email before validation
- message: String or Symbol - Custom error message

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/email_domain_checker/active_model_validator.rb', line 26

def validate_each(record, attribute, value)
  return if value.blank?

  # ActiveModel passes domain_check hash contents directly to options
  # when using validates :email, domain_check: { normalize: false }
  # So options will be { validate_domain: false, normalize: false } etc.
  normalize_option = options[:normalize] == true

  original_value = value.is_a?(String) ? value : value.to_s
  normalized_value = normalize_option ? Normalizer.normalize(original_value) : original_value

  if normalize_option && normalized_value != original_value
    record.public_send("#{attribute}=", normalized_value)
  end

  validation_options = build_validation_options(record, attribute)
  value_for_checker = normalize_option ? normalized_value : original_value
  checker = Checker.new(value_for_checker, validation_options)

  unless checker.valid?
    error_message = error_message_for(record, attribute, checker)
    record.errors.add(attribute, error_message[:key], message: error_message[:message])
  end
end