1 module ValidatesEmailFormatOf
4 LocalPartSpecialChars = Regexp.escape('!#$%&\'*-/=?+-^_`{|}~')
5 LocalPartUnquoted = '(([[:alnum:]' + LocalPartSpecialChars + ']+[\.\+]+))*[[:alnum:]' + LocalPartSpecialChars + '+]+'
6 LocalPartQuoted = '\"(([[:alnum:]' + LocalPartSpecialChars + '\.\+]*|(\\\\[\x00-\xFF]))*)\"'
7 Regex = Regexp.new('^((' + LocalPartUnquoted + ')|(' + LocalPartQuoted + ')+)@(((\w+\-+[^_])|(\w+\.[^_]))*([a-z0-9-]{1,63})\.[a-z]{2,6}$)', Regexp::EXTENDED | Regexp::IGNORECASE, 'n')
9 def self.validate_email_domain(email)
10 domain = email.match(/\@(.+)/)[1]
11 Resolv::DNS.open do |dns|
12 @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A)
14 @mx.size > 0 ? true : false
17 # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array
18 # containing one or more validation error messages.
20 # Configuration options:
21 # * <tt>message</tt> - A custom error message (default is: "does not appear to be a valid e-mail address")
22 # * <tt>check_mx</tt> - Check for MX records (default is false)
23 # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.")
24 # * <tt>with</tt> The regex to use for validating the format of the email address (default is ValidatesEmailFormatOf::Regex)</tt>
25 def self.validate_email_format(email, options={})
26 default_options = { :message => I18n.t(:invalid_email_address, :scope => [:activerecord, :errors, :messages], :default => 'does not appear to be a valid e-mail address'),
28 :mx_message => I18n.t(:email_address_not_routable, :scope => [:activerecord, :errors, :messages], :default => 'is not routable'),
29 :with => ValidatesEmailFormatOf::Regex }
30 options.merge!(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options
32 # local part max is 64 chars, domain part max is 255 chars
33 # TODO: should this decode escaped entities before counting?
35 domain, local = email.reverse.split('@', 2)
37 return [ options[:message] ]
40 unless email =~ options[:with] and not email =~ /\.\./ and domain.length <= 255 and local.length <= 64
41 return [ options[:message] ]
44 if options[:check_mx] and !ValidatesEmailFormatOf::validate_email_domain(email)
45 return [ options[:mx_message] ]
48 return nil # represents no validation errors
55 # Validates whether the value of the specified attribute is a valid email address
57 # class User < ActiveRecord::Base
58 # validates_email_format_of :email, :on => :create
61 # Configuration options:
62 # * <tt>message</tt> - A custom error message (default is: "does not appear to be a valid e-mail address")
63 # * <tt>on</tt> - Specifies when this validation is active (default is :save, other options :create, :update)
64 # * <tt>allow_nil</tt> - Allow nil values (default is false)
65 # * <tt>allow_blank</tt> - Allow blank values (default is false)
66 # * <tt>check_mx</tt> - Check for MX records (default is false)
67 # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.")
68 # * <tt>if</tt> - Specifies a method, proc or string to call to determine if the validation should
69 # occur (e.g. :if => :allow_validation, or :if => Proc.new { |user| user.signup_step > 2 }). The
70 # method, proc or string should return or evaluate to a true or false value.
71 # * <tt>unless</tt> - See <tt>:if</tt>
72 def validates_email_format_of(*attr_names)
73 options = { :on => :save,
75 :allow_blank => false }
76 options.update(attr_names.pop) if attr_names.last.is_a?(Hash)
78 validates_each(attr_names, options) do |record, attr_name, value|
80 errors = ValidatesEmailFormatOf::validate_email_format(v, options)
81 errors.each do |error|
82 record.errors.add(attr_name, error)
83 end unless errors.nil?