9.4. Redisplaying Forms with Preserved Information and Error Messages

Problem

When there’s a problem with data entered in a form, you want to print out error messages alongside the problem fields, instead of a generic error message at the top of the form. You also want to preserve the values the user typed into the form the first time.

Solution

Use an array, $errors, and store your messages in the array indexed by the name of the field.

if (! pc_validate_zipcode($_REQUEST['zipcode'])) {
    $errors['zipcode'] = "This is is a bad ZIP Code. ZIP Codes must "
                       . "have 5 numbers and no letters.";
}

When you redisplay the form, you can display each error by its field and include the original value in the field:

echo $errors['zipcode'];
$value = isset($_REQUEST['zipcode']) ?
               htmlentities($_REQUEST['zipcode']) : '';
echo "<input type=\"text\" name=\"zipcode\" value=\"$value\">";

Discussion

If your users encounter errors when filling out a long form, you can increase the overall usability of your form if you highlight exactly where the errors need to be fixed.

Consolidating all errors in a single array has many advantages. First, you can easily check if your validation process has located any items that need correction; just use count($errors). This method is easier than trying to keep track of this fact in a separate variable, especially if the flow is complex or spread out over multiple functions. Example 9-4 shows the pc_validate_form( ) validation function, which uses an $errors array.

Example 9-4. pc_validate_form( ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.