Class: EmailValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validates_email/email_validator.rb

Overview

Email validation class which uses Rails 3 ActiveModel validation mechanism.

Defined Under Namespace

Classes: Encoding

Constant Summary collapse

LocalPartSpecialChars =
Regexp.escape('!#$%&\'*-/=?+-^_`{|}~')
LocalPartUnquoted =
'(([[:alnum:]' + LocalPartSpecialChars + ']+[\.\+]+))*[[:alnum:]' + LocalPartSpecialChars + '+]+'
LocalPartQuoted =
'\"(([[:alnum:]' + LocalPartSpecialChars + '\.\+]*|(\\\\[\x00-\xFF]))*)\"'
Regex =
Regexp.new('^((' + LocalPartUnquoted + ')|(' + LocalPartQuoted + ')+)@(((\w+\-+[^_])|(\w+\.[^_]))*([a-z0-9-]{1,63})\.[a-z]{2,6}(?:\.[a-z]{2,6})?$)', Regexp::EXTENDED | Regexp::IGNORECASE, 'n')

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validates email address. If MX fallback was also requested, it will check if email is valid first, and only after that will go to MX fallback.

Examples:

class User < ActiveRecord::Base
  validates :primary_email, :email => { :mx => { :a_fallback => true } }
end


23
24
25
26
27
28
29
30
31
# File 'lib/validates_email/email_validator.rb', line 23

def validate_each(record, attribute, value)
  if validates_email_format(value)
    if options[:mx] && !validates_email_domain(value, options[:mx])
      record.errors[attribute] << (options[:mx_message] || I18n.t(:mx_invalid, :scope => [:activerecord, :errors, :messages]))
    end
  else
    record.errors[attribute] << (options[:message] || I18n.t(:invalid, :scope => [:activerecord, :errors, :messages]))
  end
end