PHP email validation with filter_var - updatedPHP email validation with filter_var - updated

Posted July 23rd, 2010 in PHP

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.

Requirements

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.

Tests

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

Related posts:

Share or Bookmark

Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.

Subscribe or Follow

Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.

Comments

blog comments powered by Disqus