Home / PHP email validation with filter_var – updated

PHP email validation with filter_var – updated

Just over a year ago I posted how to validate email addresses with PHP using filter_var instead of having to mess around with regular expressions. As pointed out in a comment, chris@example will pass validation; while that is actually a valid email address (the domain part of an email address doesn’t actually have to have dots in it, e.g. localhost) in most real situations we don’t want it to validate so this post adds a regular expression to the test to ensure the part after the @ contains a dot.


PHP 5.2.0 or higher is required for the filter_var function.

Using filter_var and check the domain part contains a dot

Here’s the code to run this test, which I’ve put into a function to make it easy to call each time:

function validateEmailAddress($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) && preg_match('/@.+./', $email);

filter_var does most of the grunt work to ensure the full email address, including the domain name part, is valid. The regular expression then checks to make sure the domain part after the @ symbol contains a . somewhere. The regular expression doesn’t need to do any further checking (e.g. to make sure there are characters after the .) because the filter_var function has already done this.


Here’s some tests to show the above working where 1 will be echoed if it’s valid, 0 if not. The result is shown at the end of the line after the // comment.

echo (int) validateEmailAddress('chris@example'); // 0
echo (int) validateEmailAddress('chris@example.'); // 0
echo (int) validateEmailAddress('chris@example.com'); // 1
echo (int) validateEmailAddress('chris@example.com.'); // 0
echo (int) validateEmailAddress('chris@example@example.com'); // 0
echo (int) validateEmailAddress('chris#example.com'); // 0
echo (int) validateEmailAddress('chris@my.multiple.dot.example.com'); // 1

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.