PHP Form Validation

This is the first part of PHP Form validation tutorial. Second part is about validating email addresses with PHP.

The validation of data that has been entered in a form is necessary in most cases. Why is important? For example, what good is holding a contest or sweepstakes if you can’t notify the winner, because he or she entered an invalid telephone number or an incorrect address. What good is having a mailing list if the e-mail addresses on it aren’t verified, and your mailing list just bounces back to you without reaching the subscribers and target audience.

Validating form entries saves you time and more importantly, it can save you money. And since somebody embossed the slogan “Time is money!”, this should be very important for your web site!

Well when should we validate? There are two types of validation; client side and server side.

For reference, client side means that you are depending on what browser the user is currently using. On the client side, validation is performed using JavaScript. And that can be very tricky, because some users turn off JavaScript support in their browsers before they even come to your site. If you encounter of one those users, client side validation won’t help you much if you try to verify data from a form because your JavaScript code will not be executed or interpreted by the browser, means you are back to square 1. Remember, the winner of your competition entered a wrong address.

This is where server side validation comes in handy. It will always work, no matter what. Of course assuming that you have access to the technology on your server. Server side validation can be done with Perl, PHP, ASP, ColdFusion, JSP and almost any other scripting language. For this tutorial, I’ll use PHP. A quite popular and easy to master server side scripting language.

Now that you know the differences between client side and server side validation, you might ask, “Why use client side validation at all?” The reason is, that especially high traffic web sites, should seize the opportunity to take off the load of the server and distribute it to the client browser. This means that if you can verify the content of a field before it is submitted and processed by the server, it makes sense to do so. And there is a user friendly side of it as well. Since most people assume that once they have clicked the submit button on a form, the process is over. A nifty popup explaining what is missing or incorrect, improves their chance of entering correct data into the form. Who wants to miss out on that lottery jackpot just because he or she forgot to verify the data they entered on an online entry form.

Enough explanation, now let’s examine the code. We’ll start with server side validation.

Server side validation with PHP

For one of my last projects, I decided to use the following validation. I checked with JavaScript if anything was inserted in a field and the used server side validation to figure out if the content was ok.

Let’s start off with my favorite server side validation. I am verifying a field for numbers only (e.g. a zip code), numbers and spaces (e.g. a telephone number), etc. Here’s my setup; I have a form.php and a error.php.


  <head> ...</head>
    <form action="error.php" method="post">
          <td>Your name:</td>
          <td><input type="text" name="your_name"></td>
          <td>Your phone:</td>
          <td><input type="text" name="your_phone"></td>
          <td>Zip code:</td>
          <td><input type="text" name="your_zip"></td>
      <input type="submit">

Pretty easy, eh? The table is not necessary, but it helps to make the form look nice.


 <?php extract($_POST); ?> 

Now for the code explanation. First of all, we have three functions to do the error checking. All three utilize a PHP function called preg_match ( We call the function, tell it what field to check and when the entered data matches the string it looks by it returns true, or false if it doesn’t.If the function returns true it does nothing, if it returns false, it outputs the error message and increments the value of $error by 1.Now what’s that really do?

 /[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\ ]+$/ 

The slashes “/” and “/” are delimiters, “^” marks the start of string or line and the Dollar sign “$” the end of the string, or line. The plus-symbol “+” means required. Knowing what the special characters mean, it actually says the following: A string, from start to finish, may contain this characters (a to z (lower case), A to Z (upper case), the numbers from 0 to 9, a dot (“.”), a hiven (“-“) and the special characters ä, ö ü (both upper and lower case) and space (” “)), and these characters only.

preg_match() is a case sensitive function, which means it treats “a” and “A” differently. I included upper (“A-Z”) and lower case (“a-z”). So called “special characters” (Special, because they have another meaning in PHP as well. But that’s another story.) have to be escaped, which means you write a backslash in front of it. For example: \- (the hiven) or \. (the dot). Other special characters are: ^[$()|*+?{\.

The other two functions are self explanatory, as they check only for numbers, and numbers and space (“\ “).

I hope you have learned the basics of server side scripting. I’m adding the full example code below, feel free to use it on your websites and projects. If you have questions or need some help with using this code, leave your comment under the post.

function check_field1($field_name_1)
  if(!preg_match("/[^a-zA-Z0-9\.\-\Ä\ä\Ö\ö\Ü\ü\ ]+$/s",$field_name_1)) return TRUE; else return FALSE;

function check_field2($field_name_2)
  if(!preg_match("/[^0-9\ ]+$/",$field_name_2)) return TRUE; else return FALSE;

function check_field3($field_name_3)
  if(!preg_match("/[^0-9]+$/ ",$field_name_3)) return TRUE; else return FALSE;

/* Validation */

// check up variable
/* get it checking */
  echo "Illegal input $your_name in 'your_name'"; $error++; // $error=$error+1;

  echo "Illegal input $your_phone in 'your_phone'"; $error++;

  echo "Illegal input $your_zip in 'your_zip'"; $error++;

if($error == 0)
  echo " The data you entred was correct, thank you!<p> Your data:<br> Your name: $your_name<br> Your phone: $your_phone<br> ZIP code: $your_zip ";

else {
  echo "Number of errors: $error";

Did you like this post? Get monthly summary of our new tutorials, posts and tips to your inbox!

Developer Resources