PHP email validation with filter_varPHP email validation with filter_var

Posted July 6th, 2009 in PHP (Updated July 23rd, 2010)

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

 

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