Simplify email validation

written by seb on June 25th, 2006 @ 09:44 AM

In ActiveRecord their’s a lot of validations functions but personnaly I missed one: validates_email_of.

As I know the simplest way to do it is by using validates_format_of in your model like this:

validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i

to make it even easier let’s add the following part of code in lib/validates_email_of.rb:

module ActiveRecord::Validations::ClassMethods
  def validates_email_of(*attr)
    validates_format_of attr, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i
  end
end

now include this library in config/enrivonment.rb

require 'validates_email_of'

what’s about now ? Just restart your server and you will be able to enjoy this new validations function for your models!

So now you may just need to do:

validates_email_of :email

That’s seem better to me, no need to copy/paste or remember the email validation regexp ;-)

Comments are closed