08.06.07

Posted in Rails at 4:25 pm by jasonb

I find myself having to validate an email address in a couple of different models. I’ve had to refine the pattern a couple of times, but don’t always remember to do it in every place, which is silly anyway. Since I don’t feel the need to delve into a new validation, like a validates_email_address or whatever, the following lets me simply reuse an existing validation in multiple places.

module EmailValidation
  def self.included(base)
    base.class_eval do
    validates_format_of :email,
      :with => %r{\A([-\w.\+]+)@((?:[-A-Za-z0-9]+)\.+[A-Za-z]{2,})\z},
      :message => 'appears to be invalid. Please verify it is correct.'
    end
  end
end

The above is just saved as email_validation.rb in lib/. Then later in my model.

class FooWithEmail < ActiveRecord::Base
  include EmailValidation
end

And no, an email address shouldn’t have A-Z in the domain portion, but I run downcase! against that attribute before saving. Users can’t really be bothered to care if a domain should be uppercase, lowercase, or mixed.

Leave a Comment

I'm the flagrant, mighty, and voluminous WP Hashcash!