Class: EmailValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/platanus/validators/email.rb

Overview

Adds the “email” validation to active record

Usage:

validates :email_col, email: true

Instance Method Summary collapse

Instance Method Details

#validate_each(_record, _attribute, _value) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/platanus/validators/email.rb', line 14

def validate_each(_record, _attribute, _value)
  return if _value.nil?
  begin
    mail = Mail::Address.new(_value)
    # We must check that value contains a domain and that value is an email address
    res = mail.domain && mail.address == _value
    tree = mail.__send__(:tree)
    # We need to dig into treetop
    # A valid domain must have dot_atom_text elements size > 1
    # user@localhost is excluded
    # treetop must respond to domain
    # We exclude valid email values like <[email protected]>
    # Hence we use mail.__send__(tree).domain
    res &&= (tree.domain.dot_atom_text.elements.size > 1)
  rescue Exception => e
    res = false
  end
  _record.errors[_attribute] << (options[:message] || "is invalid") unless res
end