Home / PHP email validation with filter_var

PHP email validation with filter_var

There’s no longer any need in PHP to create your own regular expressions to try to validate an email address; simply use filter_var() instead. This is available from PHP 5.2.0.

Update July 23rd 2010

As pointed out in a comment on this page, e.g. chris@example will validate even though it is not a regular domain. However, the domain part of an email address does not actually need to contain a dot (e.g. localhost). In real uses you would normally want to ensure the domain part includes a dot, so I have written an updated post which adds a regular expression to check for this:

Validate email addresses with filter_var

The filter_var function accepts three parameters but for testing an email address only the first two are needed. The first parameter is the data to filter, in this instance an email address, and the second the filter type, in this instance FILTER_VALIDATE_EMAIL.

filter_var function returns the filtered data or false if the filter fails. Therefore a test can be done for a valid email address by checking to see if anything is returned like so:

if(filter_var("chris@example.com", FILTER_VALIDATE_EMAIL)) {
    // it's valid so do something
else {
    // it's not valid so do something else

Here’s some more examples:

// test good email address
echo filter_var("chris@example.com", FILTER_VALIDATE_EMAIL) ? "goodn" : "badn";
// test good email address
echo filter_var("chris@a.b.c.example.com", FILTER_VALIDATE_EMAIL) ? "goodn" : "badn";
// not allowed . before @
echo filter_var("chris.@example.com", FILTER_VALIDATE_EMAIL) ? "goodn" : "badn";
// not allowed .. in domain part
echo filter_var("chris@example..com", FILTER_VALIDATE_EMAIL) ? "goodn" : "badn";
// not allowed . after @
echo filter_var("chris@.example.com", FILTER_VALIDATE_EMAIL) ? "goodn" : "badn";
// not allowed double @
echo filter_var("chris@@example.com", FILTER_VALIDATE_EMAIL) ? "goodn" : "badn";
// not allowed @ more than once anywhere
echo filter_var("chris@exa@mple.com", FILTER_VALIDATE_EMAIL) ? "goodn" : "badn";
// must have @
echo filter_var("chris#example.com", FILTER_VALIDATE_EMAIL) ? "goodn" : "badn";

And the output from the above:


Checking for a valid domain

I’ve been asked by a few people how to check if the domain is valid, as part of checking validity of an email address. One way to do it is by doing an MX record lookup on the domain (with a fallback to an A record lookup). I wouldn’t do this myself, but have written a post about how to get a mail server’s IP address with PHP to help people out should they want to.