Created
September 14, 2012 15:38
-
-
Save zambon/3722713 to your computer and use it in GitHub Desktop.
EmailFormatValidator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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