Skip to content

Instantly share code, notes, and snippets.

@zambon
Created September 14, 2012 15:38
Show Gist options
  • Save zambon/3722713 to your computer and use it in GitHub Desktop.
Save zambon/3722713 to your computer and use it in GitHub Desktop.
EmailFormatValidator
class EmailFormatValidator < ActiveModel::EachValidator
def validate_each record, attribute, value
begin
email = Mail::Address.new value
# We must check that value contains a domain and that value is an email address
result = email.domain && email.address == value
tree = email.__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 <user@localhost.com>
# Hence we use email.__send__(tree).domain
result &&= (tree.domain.dot_atom_text.elements.size > 1)
rescue Exception => e
result = false
end
record.errors[attribute] << (options[:message] || "is invalid") unless result
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment