Friday 5 December 2008

How easy is it to validate the format of an email address

The other day I had to create an admin console for creating a user object which contained the usual fields,
  • username
  • forename
  • surename
  • email
etc.

When it came to setting up the active record object to ensure that the username, forename and surname are supplied I started spec'ing the behaviour. All was moving along well.

When it came to validating the format of the email address I realised this was something I'd not done this before. Off the top of my head an email address must
  • include only one '@'
  • not include spaces
There must be a lot more to it than that.
With a bit of help from google I found there was a helpful standard that specified exactly what is a valid email address. All of a sudden my nice task of creating a scaffold for a user object had grown to include 'implementing validation for email addresses' which was going to be slightly more than,

validates_presence_of :username, :forename, :surname


The folks in the team keep talking about Rails plugins for this, that and the other. Could there be some kind sole out there that has already solved this problem?

google 'rails plugin validate email format'

and there it is!

http://code.dunae.ca/validates_email_format_of.html
A plugin called validates_email_format_of by Alex Dunae.

There has got to be a catch, how complicated is it going to be to get into my codebase and make use of it?

Here is the user class before

class User
validates_presence_of :username, :forename, :surname
end

and here is the User class after

class User
validates_presence_of :username, :forename, :surname
validates_email_format_of :email
end


I'd a few failing tests sketched out to check the email validation....all of a sudden they all pass!

Job done.
Simple and elegant, what more could you ask for?

1 comment:

Anonymous said...

'Nuff respect to the Big G!