March 15, 2006

Simple Email Validation with Regular Expressions

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 3:30 pm

Email validation in PHP can be done in a few strategies (some too exhaustive)
- Checking the syntax of the email address
- Providing the user two fields to repeat their address
- Providing an email confirmation
- Checking the domain MX records
- Verifying the mail account through communication with the MX

Usually that later few methods take too long to implement and can be open to many problems that we don’t want, such as reliance of the operating system, connectivity to the MX and DNS records (Which may cause people to get frustrated signing up with a legitimate email address). Where possible you should prompt the user for their email address twice to ensure that they have nominated the correct email free from typos that still pass basic syntax, eg. cmaeornmanderson@gmail.com opposed to cameronmanderson@gmail.com.

The syntax can be checked once again in two spots, the client side first (to give them an opportunity to fix) and then on the server side.

< input type="text" name="emailAddress" id="emailAddress" onchange="javascript:validate('emailAddress', emailAddressRegex, 'Please ensure your email address is correct');" />

As suggested in an earlier post, if we use Regular Expressions (perl) to check the format we can use the same syntax in JavaScript (for client side) as we do in PHP/VB/Java etc.

On the server side we can see that this can be compiled as a perl regular expression to match against their form submission:

< ?php

...

$emailAddressRegex = '/^[A-z0-9][\w.-]*@[A-z0-9][\w\-\.]+\.[A-z0-9]{2,6}$/'; // Could be in our standard library somewhere

$emailAddress = $_POST['emailAddress']; // Access the request->getParameter(’emailAddress’);
if(!preg_match($emailAddressRegex , $emailAddress)) {

// Add the error to our action errors

die(’Invalid email address detected’);

}


?>

We need to ensure we check the email address again on the server as it is quite easy for a legacy browser or browser with JavaScript disabled to submit the field (infact our method doesn’t stop the user from submitting for form if they know there is an error).

Your regex could be a lot more specific depending on the situation. When matching against formats it is best to read the RFC or similar. For email a good resource is located on Wikipedia.

Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Furl
  • Reddit
  • YahooMyWeb

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment