Validate Email Address Format Using PHP Regular Expression preg_match
Posted by in PHP May 12, 2011 10 Comments

This simple PHP function below will check to see if an email address is valid format/syntax or not by using PHP Regular Expression. It’s recommended to validate and check all input fields before inserting into the database especially with email address.

The function below will preg_match() PHP built in function to validate the format/systax of a email address by encoding its format in a regular expression. It looks for matches to the email pattern and will return true if matches are found, otherwise will return false.

PHP function to validate email address

<?php
function checkEmailAddress($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;
}
?>

Usage

<?php
$email = "hoan@4rapiddev.com";
 
if(checkEmailAddress($email))
	echo $email . " is a valid email address!";
else
	echo $email . " is not a valid email address!";
 
?>

Download the php-validate-email-address

Hoan Huynh is the founder and head of 4rapiddev.com. Reach him at hoan@4rapiddev.com
  • Pingback: Simple PHP Code Send Email | 4 Rapid Development

  • http://www.it2051229.org it2051229

    This code doesn’t work for format like: xxx@xxx.xx.xxx
    eg. whoever@whatever.co.uk

    • hoanhuynh

      Hi there, just did a quick check the function, it works without any issue.
      Can you paste your code somewhere?
      H2.

      • http://www.it2051229.org it2051229

        Hi, I’m sorry, I tried it and it works.. when I analyzed the expression the last letters after the “.” should be 2 to 3 characters long. I tested your code with “xxx@xxx.x.x” and an “invalid email address” appeared so I just assumed that it doesn’t work.

        • mike

          So what happens with .name addresses? should the 2,3 not be 2,4…

  • Elias

     Hi, hoanhuynh. Great job!

    I just wanted to suggest that, in order to make you function more robust, you should lowercase the e-mail before testing it.

    • http://4rapiddev.com/ Hoan Huynh

      Thank you for your suggestion. :)

  • Snolan760

    great function, i have a simular one, but it seems that “gmail” and “yahoo” don’t send. Have you had any issues with that?