Tutorial: Validating E-Mail Addresses, Including GMail “Plus” Addresses
March 21st, 2007
I’ve been asked often enough that it is worth a quick tutorial to demonstrate how to validate email addresses–or, at least, validate if an email address looks valid–that include two tricky, but valid, formats.
In addition to normal addresses, we started getting false negatives on otherwise legitimate emails that contained periods in the name as well as plus (”+”) symbols. Examples include:
first.last@somewhere.com
realname+tag@gmail.com
The latter is a very helpful trick with the GMail system that allows you to use a single address (”realname”) and tack on a tag that can be filtered or simply used in development to provide a unique address without the need to open up multiple test mail accounts (e.g. realname+tuser1@gmail.com).
In both cases, these can be legitimate addresses, so we had to modify our pattern validator. We use the following function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
function validateEmailPattern($email) {
// Filters against a pattern that conforms to a valid email address pattern
// Returns FALSE if the email address is bad; TRUE if it’s good
$retVal = false;
$pattern = ‘#^([._a-z0-9-+]+[._a-z0-9-+]*)@(([a-z0-9-_]+)(.[a-z0-9-_]+)?(.[a-z]{2,6}))$#i’;
if(preg_match($pattern, $email)) {
$retVal = true;
}
return $retVal;
}
|
This will return TRUE if the pattern appears to be valid, false if not.
Enjoy.
Sphere: Related Content
