Created
November 15, 2010 14:07
-
-
Save arronmabrey/700388 to your computer and use it in GitHub Desktop.
Email validation in Ruby On Rails 3 or Active model without regexp
This file contains hidden or 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
# via http://my.rails-royce.org/2010/07/21/email-validation-in-ruby-on-rails-without-regexp/ | |
class User < ActiveRecord::Base | |
validates :email, :presence => true, :email => true | |
end | |
# Just put a file in app/validators/email_validator.rb | |
require 'mail' | |
class EmailValidator < ActiveModel::EachValidator | |
def validate_each(record,attribute,value) | |
begin | |
m = Mail::Address.new(value) | |
# We must check that value contains a domain and that value is an email address | |
r = m.domain && m.address == value | |
t = m.__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 m.__send__(tree).domain | |
r &&= (t.domain.dot_atom_text.elements.size > 1) | |
rescue Exception => e | |
r = false | |
end | |
record.errors[attribute] << (options[:message] || "is invalid") unless r | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment