Quick links: Source code | Email address validation service
There’s a gazillion regular expressions out there that claim to validate an email address. They don’t. Doug Lovell explains why here. The function that Doug made for his article is good, but it delegates the validation of the domain part of the address to the DNS servers of the world. This is a good approach but there are three issues with it:
- The RFCs reluctantly allow you to use an IP address rather than a domain name, so you need to check for that.
- The DNS may not be available to your function at the time it needs to check the address (maybe it’s an intranet application)
- There’s no need to add extra workload to the DNS servers of the world if the address is wrongly formatted in the first place.
So I’ve come up with a PHP function that validates all parts of a given email address, according to RFCs 1123, 2396, 3696, 4291, 4343, 5321 & 5322. I’ve released it under a license that allows you to use it royalty-free in commercial or non-commercial work, subject to a few conditions (Doug Lovell’s function is All Rights Reserved by Linux Journal so you can’t use it for anything).
It’s almost certainly the first email address validator that correctly lets you put an IPv6 address in for the domain part…
I’ve also included a lot of unit tests, including all Doug Lovell’s examples and all the examples of valid addresses in RFC 3696. You might try running these test past your current email address validator. Prepare for the same nasty surprise I got
The source code is available here.