]> git.openstreetmap.org Git - rails.git/blob - vendor/plugins/validates_email_format_of/lib/validates_email_format_of.rb
Update validates_email_format_of plugin
[rails.git] / vendor / plugins / validates_email_format_of / lib / validates_email_format_of.rb
1 module ValidatesEmailFormatOf
2   require 'resolv'
3   
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')
8
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)
13     end
14     @mx.size > 0 ? true : false
15   end
16   
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.
19   #
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'),
27                           :check_mx => false,
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
31             
32       # local part max is 64 chars, domain part max is 255 chars
33       # TODO: should this decode escaped entities before counting?
34       begin
35         domain, local = email.reverse.split('@', 2)
36       rescue
37         return [ options[:message] ]
38       end
39
40       unless email =~ options[:with] and not email =~ /\.\./ and domain.length <= 255 and local.length <= 64
41         return [ options[:message] ]
42       end
43       
44       if options[:check_mx] and !ValidatesEmailFormatOf::validate_email_domain(email)
45         return [ options[:mx_message] ]
46       end
47       
48       return nil    # represents no validation errors
49   end
50 end
51
52 module ActiveRecord
53   module Validations
54     module ClassMethods
55       # Validates whether the value of the specified attribute is a valid email address
56       #
57       #   class User < ActiveRecord::Base
58       #     validates_email_format_of :email, :on => :create
59       #   end
60       #
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, 
74                     :allow_nil => false,
75                     :allow_blank => false }
76         options.update(attr_names.pop) if attr_names.last.is_a?(Hash)
77
78         validates_each(attr_names, options) do |record, attr_name, value|
79           v = value.to_s
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?
84         end
85       end
86     end   
87   end
88 end