PHP 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:
- Validating an IP address with PHP's filter_var function (Monday, August 31st 2009)
- PHP email validation using the Zend Framework (Thursday, July 9th 2009)
- List of PHP email libraries (Monday, June 1st 2009)
- Function to extract email attachments using PHP IMAP (Sunday, March 15th 2009)
- Sending email with Zend_Mail (Saturday, August 23rd 2008)
Subscribe / Follow / Email / Bookmark / Share
Use the buttons below to subscribe to my RSS feed to be notified next time something is posted, share this post with others, or subscribe by email to have my posts sent in a daily email, follow me on Twitter or follow me on Facebook.
At least one new post is usually made every day. See my posting schedule for more details.
