Class: EmailValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/active-model-email-validator.rb

Overview

This is a simple ActiveModel validator for email addresses built on top of the Mail gem. Instead of trying to devise an overly complex custom (and probably incorrect) regular expression to validate email addresses that is compliant with RFC 5321/5322—a difficult task—it instead relies on the Mail gem to parse the address. Since the Mail gem is an actively maintained library for working with email, if it can’t deal with an address it’s probably not worth attempting to send to anyways.

An additional check is performed to ensure that the domain name in the address has at least two components—that is, a top-level domain and one subdomain. The validator purposefully errs on the side of inclusivity rather than exclusivity: it might allow some invalid email addresses, but it hopefully doesn’t disallow valid addresses.

Example

The following model uses ActiveModel::Validations::PresenceValidator and ActiveRecord::Validations::UniquenessValidator to ensure the presence and uniqueness of the user’s email attribute. The third line uses EmailValidator to check that the email address is valid.

class User < ActiveRecord::Base
  validates(:email,
            :presence   => {:message => "Email can't be blank"},
            :uniqueness => {:message => 'Email must be unique'},
            :email      => {:message => 'Email must be valid'})
end

Instance Method Summary collapse

Instance Method Details

#validate_each(object, attribute, value) ⇒ Object

The interface that ActiveModel::Validations uses to invoke the validation. This method is not called directly.



20
21
22
# File 'lib/active-model-email-validator.rb', line 20

def validate_each(object, attribute, value)
  add_error_to(object, attribute) unless valid?(value)
end