PHP email validation with filter_varPHP email validation with filter_var

Posted July 6th, 2009 in PHP (Updated November 9th, 2012)

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) ? "good\n" : "bad\n";
// test good email address
echo filter_var("chris@a.b.c.example.com", FILTER_VALIDATE_EMAIL) ? "good\n" : "bad\n";
// not allowed . before @
echo filter_var("chris.@example.com", FILTER_VALIDATE_EMAIL) ? "good\n" : "bad\n";
// not allowed .. in domain part
echo filter_var("chris@example..com", FILTER_VALIDATE_EMAIL) ? "good\n" : "bad\n";
// not allowed . after @
echo filter_var("chris@.example.com", FILTER_VALIDATE_EMAIL) ? "good\n" : "bad\n";
// not allowed double @
echo filter_var("chris@@example.com", FILTER_VALIDATE_EMAIL) ? "good\n" : "bad\n";
// not allowed @ more than once anywhere
echo filter_var("chris@exa@mple.com", FILTER_VALIDATE_EMAIL) ? "good\n" : "bad\n";
// must have @
echo filter_var("chris#example.com", FILTER_VALIDATE_EMAIL) ? "good\n" : "bad\n";

And the output from the above:

good
good
bad
bad
bad
bad
bad
bad

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.

Related posts:

Comments

blog comments powered by Disqus