There are many possible ways to show the user they have entered incorrect information on a form. Asterisks are common, but when doing server-side validation I prefer to use something with a little more visual impact.

First, we are continuing on from our last lesson: we should have both a form.html page and a formhandler.php page. Take the code for the form from the first page, and place if as the result of finding an error in formhandler.php:

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:

Checking information entered by users into a form is referred to as form validation. There are many different forms of validation, but the basic pattern match function in PHP is eregi, which stands for “evaluate regular expression, case insensitive”. However, as of PHP 5.3, eregi is deprecated, in favour of preg_match, strstr, and related functions, for technical reasons I won’t go into here. I’ll use preg_match for examples here: the function should work in both earlier and later versions of PHP, and you don’t want to be caught short if your hosting provider upgrades PHP to 5.3 or greater on their servers. Essentially the difference is that patterns used with preg_match must be surrounded by delimiter characters (/ /); in eregi, no delimiter character is used.

No matter which version of the function you choose to use, it is usually employed as the condition in an if statement.