Skip to content

How to: Use a custom email validator with Devise

Sam Jewell edited this page May 3, 2019 · 8 revisions

Note: This approach has been used with Devise 1.5.4 under Rails 3.2.12, YMMV.

Email validation in a production apps is challenging because the RFC is complex, and in the real world different email sub-systems differ in their adherence to the RFC spec. It is not uncommon for a "valid" email to be rejected by a system that may validate email addresses with a too-narrow subset of rules.

The Devise email validator is intentionally relaxed to reduce the likelihood of rejecting a valid email, but, as a result, may permit users to register with an email address that is not deliverable. One specific example is [email protected],. Whether or not that address is valid according to the RFC, it clearly cannot be delivered. (And since the comma key is next to the "m" key on most keyboards, it's not that hard for a user to type ".co," instead of ".com")

Rails permits custom validators, so it is quite simple to add your own custom email validator, and no change to Devise is necessary (as long as you want Devise's built-in validator to also be applied). You'll get the union of the two validators, eg, an email has to pass both validators. If your custom validator is "more strict" than Devise's validator (as in this example), your app will have the benefit of the stricter validation automatically.

If your goal is to supplement, but not replace, the Devise email validation, the approach is simpler:

Add to your User model:

validates :email, :presence => true, :email => true

(Update 2015-Mar-24: the :tree method used was private and is no longer available. A limited check/hack would be to ensure the domain contains at least one '.')

# 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, the domain has at least
      # one '.' and that value is an email address      
      r = m.domain.present? && m.domain.match('\.') && m.address == value

      # Update 2015-Mar-24
      # the :tree method was private and is no longer available.
      # 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   
      r = false
    end
    record.errors[attribute] << (options[:message] || "is invalid") unless r
  end
end
  1. (Be sure to restart your server)
Clone this wiki locally