Class: EmailValidator

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

Overview

Validator for email

Instance Method Summary collapse

Instance Method Details

#allow_idn?Boolean

check the options for idn support

Returns:

  • (Boolean)


13
14
15
# File 'lib/rails_email_validator.rb', line 13

def allow_idn?
  options[:allow_idn].nil? or options[:allow_idn] == true
end

#convert_idn(domain_part) ⇒ Object

convert an unicode domain_part to asccii for validation



28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/rails_email_validator.rb', line 28

def convert_idn(domain_part)
  if allow_idn?
    # idn suport if available
    begin
      require 'idn'
      # encode domain part
      return IDN::Idna.toASCII(domain_part)
    rescue LoadError
    rescue IDN::Idna::IdnaError
    end
  end
  domain_part
end

#has_mx?(domain) ⇒ Boolean

validate if an mx exists on domain

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
# File 'lib/rails_email_validator.rb', line 18

def has_mx?(domain)
  require 'resolv'
  mx = []
  Resolv::DNS.open do |dns|
    mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
  end
  not mx.nil? and mx.size > 0
end

#validate_each(record, attribute, value) ⇒ Object

main validator for email



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/rails_email_validator.rb', line 43

def validate_each(record, attribute, value)
  unless value.blank?

    # pre var
    valid = true
    local_part = nil
    domain_part = nil

    if valid
      # split local and domain part
      (local_part, domain_part) = value.to_s.split('@', 2)
    end

    domain_part = convert_idn domain_part

    if valid
      # check syntax
      valid = false unless local_part =~ /\A[a-z0-9!\#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!\#$%&'*+\/=?^_`{|}~-]+)*\Z/i
      valid = false unless domain_part =~ /\A(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\Z/i
    end

    # check mx
    if valid and validate_mx?
      valid = false unless has_mx? domain_part
    end

    # email valid
    record.errors.add(attribute, :invalid) unless valid
  end
end

#validate_mx?Boolean

check the options for do mx validation

Returns:

  • (Boolean)


8
9
10
# File 'lib/rails_email_validator.rb', line 8

def validate_mx?
  options[:validate_mx].nil? or options[:validate_mx] == true
end