Locksmack

Technology, Web Development, Philosophy and more…

PHP: Check for valid email address

After searching the deepest and darkest parts of the web for a simple function to validated an email address in PHP, I finally found it:

function check_email_address($email) {
    if(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/", $email)){
        return true;    
 }    
 return false;
}

I can’t recall where I got it from (I will give credit if I figure out where), but it was the last of about half a dozen that I tried. Many didn’t work at all, some used depreciated functions and others were just messy. There are some fancier versions that check not only if the email address is in a valid format, but also if it exists, but that was overkill for what I wanted to do.

The function returns a boolean, so you can easily use it in an if statement:

$email = "john@example.com";
if(check_email_address($email)){
 echo "Email is valid!";
} else {
 echo "Email is invalid";
}

Nice and simple :) We could add more features, but I like to think that mankind is smart enough to type their email address into a form correctly…..yeah right.

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Switch to our mobile site