PHP5 Email Validation

10 Feb
2009

In prior version of PHP you had to use some regex solution to validate an email address, now in PHP5 it’s as simple as:

function isValidEmail($email){
 return filter_var(filter_var($email, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);
}

if(isValidEmail('email@domain.com')){
//valid
} else {
//not valid
}

I’ve been using PHP5 ever since it was released but didn’t look into the PECL Filter extension until recently. Pretty handy.

Please note that I also added the FILTER_SANITIZE_EMAIL filter which removes all illegal e-mail characters from a string. This is not needed if you only want to validate and not clean the input. :)

4 Responses to PHP5 Email Validation

Avatar

dewi was here

February 11th, 2009 at 7:40 am

first comment :p
dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here dewi was here

Avatar

cristian

May 19th, 2009 at 7:18 am

Well, try:

echo filter_var(filter_var(“John(Doe)@exa\\mple.com”, FILTER_SANITIZE_EMAIL), FILTER_VALIDATE_EMAIL);

still is not a valid email address (wrong domain).

Note that this these functions only validate the structure of email address or URL strings, they don’t check if the associated domains actually exist.

Avatar

Bill

May 21st, 2009 at 12:54 pm

@cristian: you’re absolutely right. I was not trying to imply that it checks if a domain exist but I should have been more clear on this. Sorry about that. Also note that even if you check if the domain exists via cURL or method of your choice, it still would not prove it’s a valid working email.

Would you like me to post an example to check if a domain exists?

Avatar

PHP: Check if a URL exists with cURL | Bill Richards

August 9th, 2009 at 6:29 pm

[...] my previous post about email validation one user pointed out that this will not actually validate if a website’s domain actually [...]

Comment Form

top