PHP: Validate Email Address and Phone Number

Updated for PHP 5+! Do you have a form and need to validate an email address or phone number? Here we have an example of how to do just that…validate an email address and validate a phone number — for Both standard phone numbers and 800/866/900/etc numbers!

Validating phone numbers and email addresses with regex

Our tutorial takes advantage of PHP’s built in regular expressions (regex) function.

Here is the heart of the code (mainly the regex patterns) that we are going to use. If you are just needing a brief reminder of these patterns then you don’t have to read any further! You’re welcome.

<?php

// validate a phone number
if( !preg_match("/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i", $phone) ) { 
	echo 'Please enter a valid phone number';
}

// validate an email address
if( !preg_match("/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i", $email) ) {
	echo 'You have entered and invalid email address';
}

?>

A more complete example

Here is an entire working example of how to validate a phone number and email address with PHP using regular expressions (regex). While there were many different ways to accomplish this task, we chose a method that was easy to use (and reuse!) easy to understand, and provided the best opportunity for you to learn some PHP fundamentals.

Our Code

For all of the impatient readers, here is the final code that we will end up with. For those who actually want to learn, we will go over each line of the code and describe what it does.

validate_phone_and_email.php

<?php
/**
 * function to check the validity of the given string
 * $what = what you are checking (phone, email, etc)
 * $data = the string you want to check
 */	
function isValid( $what, $data ) {

	switch( $what ) {

		// validate a phone number		
		case 'phone':
			$pattern = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i";
		break;
		
		// validate email address
		case 'email':
			$pattern = "/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i";
		break;
			
		default:
			return false;
		break;
	
	}
	
	return preg_match($pattern, $data) ? true : false;
		
}

$errors = array();

if( isset($_POST['btn_submit']) ) {
	
	if( !isValid( 'phone', $_POST['phone'] ) ) {
		$errors[] = 'Please enter a valid phone number';		
	}
	
	if( !isValid( 'email', $_POST['email'] ) ) {
		$errors[] = 'Please enter a valid email address';		
	}
	
}

if( !empty($errors) ) {
	foreach( $errors as $e ) echo "$e <br />";
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Phone Number: <input type="text" name="phone" />
Email Address: <input type="text" name="email" />
<input type="submit" name="btn_submit" value="submit" />
</form>

The form

For our tutorial we are using a basic HTML form to capture the phone number and email address that we are wanting to validate:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Phone Number: <input type="text" name="phone" />
Email Address: <input type="text" name="email" />
<input type="submit" name="btn_submit" value="submit" />
</form>

Notice that our form action is set to $_SERVER['PHP_SELF'] (Line 1). This makes the form POST back to the same page that it’s displayed on. More on this later…

The important thing to note about the input fields are the names (lines 2 & 3) — phone and email

Creating the isValid() function

To validate the email address and phone number we are going to use PHPs regular expressions. To make the code reusable we are going to drop it into a function that we can call whenever we need it. Another great advantage of doing it this way is that we can very easily expand the function to validate other types of data like URLs, credit card numbers, and more!

<?php
function isValid( $what, $data ) {

	switch( $what ) {

These lines are pretty basic and should be easily readable if you have any experience at all with PHP. Basically, line 2 create our function and tell it to expect two parameters — $what we are checking for (phone, email, etc), and the actual $data that we want to validate.

Line 4 — switch( $what ) { — will run $what through a switch statement to choose which REGEX pattern to use depending on what we are validating.

Validating phone numbers

		// validate a phone number		
		case 'phone':
			$pattern = "/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i";
		break;

I am going to briefly explain the regular expressions patterns that we will be using. However, besides being a general pain in the ass, REGEX is also out of the scope of this tutorial. If you would like to learn more there are several good tutorials available. Anyways, on to our patterns…

line 7: The pattern that we use to check phone numbers will check both “standard” numbers — 555-123-4567 — as well as 800 numbers — 1-800-555-1234:
/^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$/i
The slashes (/) at the start and end are the delimiters that signal where our pattern starts and ends. The caret (^) indicates the beginning of the string we want to check. ([1]-)? is asking “is there a ’1′ followed by a hyphen”? The question mark at the end makes this portion optional. In other words, if it’s not there — meaning that it’s not an 800 number — it won’t immediately assume that the phone number is invalid. The next part [0-9]{3}- is looking for ONLY numbers [0-9] and there must be three {3} of them. Now, the added hyphen after the {3}- makes it so that hyphens are required in the phone number. You can change this if you do not like this behavior.

The following [0-9]{3}- is doing the same thing — making sure there are three numbers and a hyphen. Now, if you will notice, the last of these ends with {4}. As you my have guessed, this requires there to be four digits in the last part of the number. The $ at end signifies that this is the end of our string.

The i after the final slash (/i) is a switch that tells regex to perform a case-insensitive search. In other words “aaa” would be considered the same as “AAA”. This isn’t too important when validating a phone number, but you should definitely include it when validating an email address.

Validating an email address

		// validate email address
		case 'email':
			$pattern = "/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/i";
		break;

The pattern for validating an email address is a bit more complicated. Essentially, it makes sure the email address contains any amount of letters or numbers, followed by an @ symbol, followed by any letters or numbers (the domain name), followed by a . and then ending with any combination of 2 or 3 letters (for the TLD).

Finishing up the isValid() function

	}
	
	return preg_match($pattern, $data) ? true : false;
}
?>

This part is simple…we use preg_match to determine if the string ($data) matches the given pattern ($pattern). If it matches, we return TRUE. Otherwise we return FALSE.

PHPs preg_match function requires two parameters. The first parameter is the REGEX pattern you’ll be using. The second is the string that you want to validate. In our case, we use $pattern which is the variable that we assigned our pattern to in our switch statement, and $data, which is the string that we passed to the isValid function.

Using the isValid() function

Using our newly created isValid() function is simple. As mentioned above, the isValid() function is setup to return true if the given data is valid and false if it’s not valid. Due to this nature, it’s probably best to use this function in an if/else statement like so:

...
if( isValid('phone', '555-123-1234') ) {
     echo "phone number is valid";
} else {
     echo "phone number IS NOT valid!";
}
...

or even..

...
echo isValid( 'phone', '555-123-1234' ) ? "Valid phone number" : "Invalid phone number!";
...

Finishing up our code…

Create an array to hold any errors

$errors = array();

See if the form was submitted. We are checking for the presence of $_POST['btn_submit'] which is what we named the button in our form.

if( isset($_POST['btn_submit']) ) {

If the form was submitted then we use our isValid() function to check whether or not the phone number and email are valid. If the submitted data is NOT valid we will append an error message to our $errors array:

	if( !isValid('phone', $_POST['phone']) ) {
		$errors[] = 'Please enter a valid phone number';		
	}
 
	if( !isValid('email', $_POST['email']) ) {
		$errors[] = 'Please enter a valid email address';		
	}

Next, we check for and print out any errors. First, we check to see if the $errors array is empty. If it’s NOT empty, then we have errors that we need to display. We’ll use a foreach statement to do this:

if( !empty( $errors ) ) {
	foreach( $errors as $e )  echo "$e 
"; } ?>

Last, but certainly not least, we have our form. As mentioned above, we have set the form action to <?php echo $_SERVER['PHP_SELF']; ?>. This will cause the form to be submitted back to the page where it is being displayed. This is exactly what we want since our code is setup to look for the variables that will be POSTed by the form.

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Phone Number: <input type="text" name="phone" />
Email Address: <input type="text" name="email" />
<input type="submit" name="btn_submit" value="submit" />
</form>

There you have it, folks! A complete example of how to validate a phone number and email address using PHP and regex. While it may look like a lot, the code is really simple — and less than 60 lines, including liberal spacing!

Download the source: validate-phone-and-email.txt

About the Author

Mike Everhart is the President and CEO of PlasticBrain Media LLC. He utilizes his knowledge, skills, and over 10 years of experience to help create awesome websites and web-based applications for businesses of all sizes. Mike currently helps manage over 100 websites for clients, his businesses, and his own personal use. He also prides himself in being the best at what he does in his surrounding area. Some might say that he's arrogant, but Mike prefers to call it confident.

Mike specializes in standards-based web design, programming, search engine optimization or SEO, social marketing, and online advertising. His preferred languages are PHP, MySQL, jQuery, xHTML, HTML5, CSS2, and CSS3. Mike is also a WordPress guru, having personally made over 200 custom WordPress themes, and several plugins.

Mike's main motivation, aside from his family, and love of money, is the feeling he gets knowing that a client is truly satisfied with the work that he's done.

View all posts by Mike Everhart

22 Responses to "PHP: Validate Email Address and Phone Number"

Please enable javascript to get the full experience of our site.