Class: EmailValidator

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.disposable_emailsObject



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

def self.disposable_emails
  @@disposable_emails ||= YAML.load_file(File.expand_path("../../disposable_emails.yml",__FILE__))
end

Instance Method Details

#default_optionsObject



12
13
14
# File 'lib/valid_email2.rb', line 12

def default_options
  { regex: true, disposable: false, mx: false }
end

#error(record, attribute) ⇒ Object



51
52
53
# File 'lib/valid_email2.rb', line 51

def error(record, attribute)
  record.errors.add(attribute, options[:message] || :invalid)
end

#validate_each(record, attribute, value) ⇒ Object



16
17
18
19
20
21
22
23
24
25
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/valid_email2.rb', line 16

def validate_each(record, attribute, value)
  return unless value.present?
  options = default_options.merge(self.options)
  email = Mail::Address.new(value)

  if email.domain && email.address == value
    tree = email.send(:tree)

    # Valid email needs to have a dot in the domain
    unless tree.domain.dot_atom_text.elements.size > 1
      error(record, attribute)
    end
  else
    error(record, attribute)
  end

  if options[:disposable]
    if self.class.disposable_emails.include?(email.domain)
      error(record, attribute)
    end
  end

  if options[:mx]
    mx = []

    Resolv::DNS.open do |dns|
      mx.concat dns.getresources(email.domain, Resolv::DNS::Resource::IN::MX)
    end

    unless mx.any?
      error(record, attribute)
    end
  end
end