PHP - Validating Email Address and Phone Number
Last Updated: September 20, 2008 – 4:20 amDo 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!
Getting Started
Our final product will contain three different parts: An HTML form, the php that validates the form, and the css that styles everything. The PHP and the HTML form are setup to go in the same file but you can (and should!) copy the CSS to your existing stylesheet.
The Form

Our form is a typical one. One like you have seen on websites everywhere. It includes fields for name, phone number, email address, and a message.
As you can see in the picture, we are making some of the fields required. Aside from that, we will also be validating the name, phone number, and email address (and making sure the message is not left blank.)
The Code
The code is pretty straightforward — and heavily commented — so take a look. After you are finished looking at it we will go over what it does and exactly how it does it.
style.css
/* "holds" everything... in this case it just determines the overall width*/
#holder {
width: 600px;
}
/* styles the text boxes and text area */
input.text, textarea {
width: 300px;
border: 1px solid #ccc;
margin: 0 0 10px 0;
padding: 0 0 0 3px;
height: 24px;
font-size: 16px;
}
/* Set the height for the text area */
textarea {
height: 150px;
}
/* Make the submit button push to the right side of the form */
input#submit {
margin: 0 0 0 320px;
}
/* style the labels that are in front of the text boxes */
label {
width: 90px;
text-align: right;
display: block;
float: left;
font-size: 14px;
margin: 0 5px 0 0;
padding: 4px 0 0 0;
}
/* Make our "required" labels red */
span.req {
color: #ff0000;
}
/* The "status bar" at the top -- blue for messages */
span.message {
display: block;
background-color: #DFF1FF;
border: 2px solid #8FD7FF ;
color: #333;
margin: 0 0 20px 0;
padding: 7px;
text-align: left;
font-size: 14px;
}
/* The "status bar" at the top -- red for errors */
span.error { /* red */
display: block;
background-color: #FFBFC2;
border: 2px solid #FF6F75 ;
color: #444;
margin: 0 0 20px 0;
padding: 7px;
text-align: left;
font-size: 14px;
font-weight: bold;
}
/* set the margin and padding for the ul's in the status bar */
span ul {
margin: 0;
padding: 0 0 0 20px;
}
/* set the margin and padding for the li's in the status bar */
span ul li {
margin: 0;
padding: 0;
}
validate_form.php
<?php
// Updated 2008-09-21
// Validate Email Address and Phone -- ©2008 PlasticBrain
// www.plasticbrain.net
// ---------------------------------------------------------
// see if the "submit" button was pushed
if (isset($_POST['submit'])) {
// gather the POST data
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$message = $_POST['message'];
// make sure our variables are empty
$error = array();
$msg = "";
$error_msg = "";
// validate name
if (strlen(trim($name)) > 0) {
if(!ereg('^[a-z A-Z]+$', $name)){
$error['name'] = "Your name contains invalid characters. Only letters are allowed! "; // invalid characters
}
} else {
$error['name'] = "Please enter your name!"; // the name field was left blank
}
//validate phone number
if (strlen(trim($phone)) > 0) {
if(!ereg('^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$', $phone)){ //
$error['phone'] = "Your phone number is not valid!";
}
}
//validate email
if (strlen(trim($email)) > 0) {
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error['email'] = "Your email address is not valid!";
}
} else {
$error['email'] = "Please enter your email address!";
}
// Check the message
if (!strlen(trim($message)) > 0) {
$error['message'] = "Please enter your message!";
}
//
// We are finished validating the form. Now, let's see if there were any errors.
// If there are no errors, we proceed. If there are errors, we will print
// them to the screen and highlight the fields in the form
//
if (empty($error)) {
// There were no errors!
$msg = "Congrats, $name! There were no errors in the form!";
} else {
// There were errors, let's set the styles for the fields
$error_msg = "<ul>\n";
foreach($error as $field => $message) {
$style[$field] = "border: 1px solid #ff0000 !important;;
background-color: #FFEFEF !important;";
$error_msg .= "<li>$message</li>\n";
}
$error_msg .= "</ul>\n";
}
} // end check for submit button...
//
// Now we print the form...
//
?>
<div id="holder">
<?php
if (isset($error_msg) && strlen(trim($error_msg)) > 0) {
echo "<span class=\"error\"> $error_msg </span>\n";
}
if (isset($msg) && strlen(trim($msg)) > 0) {
echo "<span class=\"message\"> $msg </span>\n";
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<label>Name<span class="req">*</span> </label>
<input type="text" class="text" name="name" style="<?php echo $style['name']; ?>" value="<?php if (isset($_POST['name'])) { echo $_POST['name']; } ?>" /><br />
<label>Phone Number</label>
<input type="text" class="text" name="phone" style="<?php echo $style['phone']; ?>" value="<?php if (isset($_POST['phone'])) { echo $_POST['phone']; } ?>" /><br />
<label>Email<span class="req">*</span> </label>
<input type="text" class="text" name="email" style="<?php echo $style['email']; ?>" value="<?php if (isset($_POST['email'])) { echo $_POST['email']; } ?>" /><br />
<label>Message<span class="req">*</span> </label>
<textarea name="message" style="<?php echo $style['message']; ?>" cols="" rows=""><?php if (isset($_POST['message'])) { echo $_POST['message']; } ?></textarea><br />
<input type="submit" name="submit" id="submit" value="submit →" />
</form>
</div>
Was the Form Submitted?
Let’s take a look at the code. Starting at the top:
if (isset($_POST['submit']))
When the page is loaded, this line of code checks the POST data — if there is any — to see if the “submit” button was pushed. If you were wondering how our PHP code knew the name of our button then take look at the HTML code for the form. You will notice that we gave our button the name “submit”. If the button was pressed, we continue on to the next lines of code:
// gather the POST data
$name = $_POST['name'];
…// make sure our variables are empty
$error = array();
…
As the comments suggest, these lines get the POST data and makes sure that our variables that we will be using are empty.
Validate the Data
Now we need to take all of the data that was submitted and make sure it meets our guidelines. If it doesn’t we need to let the user know!
Name
if (strlen(trim($name)) > 0) {
First, we remove any whitespace from the name. Then we make sure that it was not left blank by verifying that it’s length (minus any spaces) is at least 1 character. You can increase this number for a more accurate judgement.
if(!ereg('^[a-z A-Z]+$', $name)){
If the user did enter a name, we then use ereg to make sure that it matches a certain pattern. In this case the pattern is: ^[a-z A-Z]+$
The ^ signals the beginning of the string. The [a-zA-Z] tells us that we can only have upper or lowercase letters from A to Z. The $ signals the end of the string.
$error['name'] = "Your name contains invalid characters. Only letters are allowed! "; // invalid characters }
If the name does not match the pattern we add an error message to our “error” array as error['name']
} else {
$error['name'] = "Please enter your name!"; // the name field was left blank
}
Remember, the name was required! If it was left blank, we add a (slightly different) error message to the array.
Phone Number
To check the phone number, we use ereg again, but with a different pattern: ^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$
This pattern will check both “standard” numbers (555-555-1234) and 1-800 style numbers. Let’s take a look.
if(!ereg('^([1]-)?[0-9]{3}-[0-9]{3}-[0-9]{4}$', $phone)){ //
$error['phone'] = "Your phone number is not valid!";
}
Again, the ^ signals the start, and the $ signals the end. ([1]-)? says that there might be one number and a hyphen at the beginning (for 1-800 numbers) but there might not be. [0-9]{3}- verifies that there are numbers [0-9] and that there are three of them {3} followed by a hyphen -. If the number does not match our pattern, we set an error for it in our array.
Email Address
Since email addresses are a bit more complicated than phone numbers, we will use a similar, yet slightly different function. We use eregi instead of ereg. They are the exact same function, except eregi ignores case when matching. This prevents us from having to type [a-zA-Z] each time.
if (strlen(trim($email)) > 0) {
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error['email'] = "Your email address is not valid!";
}
} else {
$error['email'] = "Please enter your email address!";
}
The pattern here is a bit more complicated. Think you can figure it out on your own? I Think you can
Message
if (!strlen(trim($message)) > 0) {
$error['message'] = "Please enter your message!";
}
This one is simple enough. We remove the whitespace and make sure that it has as least one character. If not, we add an error.
Checking for Errors
Now that we have validated all of the submitted data it’s time to either let the user know of any errors, or continue with our script if there were none.
if (empty($error)) {
This checks to see if our array $error contains any data. If it is empty, we know that there were no errors:
// There were no errors! $msg = "Congrats, $name! There were no errors in the form!";
Here, we simply display a nice message saying that there were no errors. In real life, this is where you would put the code to do whatever it is that you are actually wanting to do with this form — send an email, add data to a database, submit comments to a blog post, whatever.
} else {
// There were errors, let's set the styles for the fields
If we get to this point, it means that our $error array is not empty — it’s holding data about the errors on the form.
$error_msg = "<ul>\n";
foreach($error as $field => $message) {
$style[$field] = "border: 1px solid #ff0000 !important;;
background-color: #FFEFEF !important;";
$error_msg .= "<li>$message</li>\n";
}
$error_msg .= "</ul>\n";
}
Here, we use a new variable — $error_message — to create an unordered list that displays each of the messages. Then, we use foreach to loop through our $error array. For each error it takes the key of the array (which is the field name) and the value of the array (which is the error that we set) and adds it to our list. At the same time that this happens, you will notice that we create yet another array — actually, we create several arrays — called $style[$field]. Do you see what we did there? We created an array called style for each of the fields with an error. Why did we do that? Well, that’s how we determine which fields to highlight on the form to let the user know about their errors. We could further extend this and display the error messages under each text box, create individual styles for each text box, and so on. But, we have dragged this one out long enough so that will have to wait for another time!
Printing the Form
I know some of you are thinking “Wait a minute… we need the form to be shown FIRST, so why is it LAST?!!1!!one!” Well, we have a good answer for that. Our code comes first because the action for our form is set to post back to the same page in which it originated from. This means that when you submit the form, essentially the page is just reloaded. That’s why the PHP needs to be at the top. To catch all of the POSTed data. Also, with it setup this way you are able to use a header redirect if the form is submitted without errors (say, for a login script).
Another thing you will notice before we even get to the form is that we have some more code:
<div id="holder">
<?php
if (isset($error_msg) && strlen(trim($error_msg)) > 0) {
echo "<span class=\"error\"> $error_msg </span>\n";
}
if (isset($msg) && strlen(trim($msg)) > 0) {
echo "<span class=\"message\"> $msg <span>\n";
}
?>
This is the code that we use to check for, and display, our error messages (and in this case our message for success.) Notice that we check for the string that we created — $error_msg — and not the $errors array. If it is set then we drop it between some span tags that we define in the CSS. Also notice our beginning <div id=”holder”>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<label>Name<span class="req">*</span></label>
<input type="text" class="text" name="name" style="<?php echo $style['name']; ?>" value="<?php if (isset($_POST['name'])) { echo $_POST['name']; } ?>" /><br />
<label>Phone Number</label>
<input type="text" class="text" name="phone" style="<?php echo $style['phone']; ?>" value="<?php if (isset($_POST['phone'])) { echo $_POST['phone']; } ?>" /><br />
...
<input type="submit" name="submit" id="submit" value="submit →" />
</form>
</div>
Here we have your basic HTML form, with a bit of added flavor… First, we have the form action that we mentioned earlier: <?php $_SERVER['PHP_SELF']; ?> tells the form to submit back to the same page.
After that, we have a standard label and an input (text) box. Notice that for required fields, we add <span class=”req”>*</span> to the labels for our red asterisk *.
The main thing to pay attention to here is the style for each of the inputs. Notice that it’s set as style=”<?php echo $style['name']; ?> (or whatever the input’s name is) We use this in conjunction with the $style array that was created earlier to highlight the incorrect fields. With me so far? Good!
Last is our submit button. The important thing here is the name that we give it. It must match whatever it is that you are checking for at the beginning of the script –if (isset($_POST['submit']))!
So, What Does This Thing Look Like?
Glad you asked! Let’s take a look:
If you just copy and past the code you will get results similar to what you see here. Nothing too fancy. We just display each error message, and change the borders to a bold red and the backgrounds to a light red on those fields with errors.
Get Creative!
With a little tweaking, you can do other, fancier stuff like:


