PHP email validation with filter_varPHP email validation with filter_var

Posted July 6th, 2009 in PHP

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.

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

Related posts: