I’m Dudley Storey, the author of Pro CSS3 Animation. This is my blog, where I talk about web design and development with , and . To receive more information, including news, updates, and tips, you should follow me on Twitter or add me on Google+.

web developer guide

my books

Book cover of Pro CSS3 AnimationPro CSS3 Animation, Apress, 2013

my other blogs

Massive Head Canon: Intelligent discussion of movies, books, games, and technology.

my projects

A Sass color keyword system for designers. Replaces CSS defaults with improved hues and more memorable, relevant color names.

CSSslidy: an auto-generated #RWD image slider. 3.8K of JS, no JQuery. Drop in images, add a line of CSS. Done.

tipster.ioAutomatically provides local tipping customs and percentages for services anywhere.

PHP Form Validation: Checking Fields

php / forms

Estimated reading time: 2 minutes, 48 seconds

Now that we know how to use pattern matching with regular expressions, we can use to check the information that the user as entered into a form. For this example, I will keep the form fields very simple: we want to check that the user’s first name, postal code, email address, and province have been filled out correctly.

For the purposes of clarity, I will also do the form validation on a separate page from the form itself. The form will be on a page called form.html, and the receiving page, the action of the form, will be formhandler.php This would typically not be the case: it's much more common to do all of these operations on a single page, but that can be a little confusing at first, and is an approach I will cover in a later entry.

First, the code for the form, which is a simple document:

<form method="post" action="formhandler.php">
<legend>Please enter your information</legend>
<label for="firstname" accesskey="f">First name</label>
<input type="text" name="firstname" id=firstname" size="30" maxlength="28" />
<label for="postalcode" accesskey="p">Postal code</label>
<input type="text" name="postalcode" id=postalcode" size="9" maxlength="7" />
<label for="email" accesskey="e">eMail address</label>
<input type="email" name="email" id=email" size="50" maxlength="48" />
<label for="province" accesskey="t">Province / Territory</label>
<select name="province" id=province">
<option value="" selected="selected">-- select one --</option>
<option value="AB">Alberta</option>
<option value="BC">British Columbia</option>
<option value="MB">Manitoba</option>
<option value="NB">New Brunswick</option>
<option value="NL">Newfoundland and Labrador</option>
<option value="NS">Nova Scotia</option>
<option value="NT">Northwest Territories</option>
<option value="NU">Nunavut</option>
<option value="ON">Ontario</option>
<option value="PE">Prince Edward Island</option>
<option value="QC">Québec</option>
<option value="SK">Saskatchewan</option>
<option value="YT">Yukon</option>
<input type="submit" value="Go" />

Next, the page that is the action for this form, formhandler.php. The first thing I will do is simplify the variables I have received, just to make life slightly easier, as well as creating some variables that we will use later:

$firstname = $_POST['firstname'];
$postalcode = $_POST['postalcode'];
$email = $_POST['email'];
$province = $_POST['province'];
$errorflag = false;
$errorfirstname = false;
$errorpostalcode = false;
$erroremail = false;
$errorprovince = false;

I’m then going to set up the patterns for the fields:

$namepattern = “/^[[:alpha:].’ -]{2,15}$/”;
$postalpattern = "/[A-Z][0-9][A-Z][0-9][A-Z][0-9]/";
$emailpattern =

As the user may have entered a hyphen or a space when entering her postal code, I’m going to create an array of those values. I’ll then remove any occurrences of hyphens or spaces with nothing at all (effectively removing them) and place the result, converted to uppercase, in a variable:

$rem_array = array(" ","-");
$temp_postalcode = strtoupper(str_replace($rem_array,"", $postalcode));

Finally, I am going to check that the entered information matches the expected patterns or values. If they do not, I’ll want to do two things:

  1. Record a specific error for that form field;
  2. Record that there is something wrong with the form as a whole.

Naturally, there are more efficient ways of doing this, but I find this method to be the easiest to understand at first. The tests would be something like the following:

if (!preg_match($namepattern, $firstname))
	{ $errorflag = true; $errorfirstname = true; }
if (!preg_match($emailpattern, $email))
	{ $errorflag = true; $erroremail = true; }

Note that we test our cleaned-up $temp_postalcode variable, not the original postal code:

if (!preg_match($postalpattern, $temp_postalcode))
	{ $errorflag = true; $errorpostalcode = true; }

There’s no need to pattern-test $province, as that will always be a known set of values; if the user has not chosen a province or territory, $province will be blank:

if (!$province) { $errorflag = true; $errorprovince = true; }

Now we have $errorflag recording if there is something wrong with our form. We can now decide whether to process the information, or to alert the user that she has made an error:

if ($errorflag) {
	/* show the form again */
} else {
	/* process the form information */
comments powered by Disqus

This site helps millions of visitors while remaining ad-free. For less than the price of a cup of coffee, you can help pay for bandwidth and server costs while encouraging further articles.