Displaying error messages
Changes are required to display the errors that are saved in the session variable $errors in the validation script. We have added the function fieldError( ) to help display the error messages above the <input> fields. The function takes two parameters: $errors, which is the associative array of error messages, and $fieldName, which is the index into the array.
function fieldError($fieldName, $errors)
{
if (isset($errors[$fieldName]))
echo
"<font color=RED>$errors[$fieldName]</font><br>";
}
This function tests if the indexed error message exists and, if so, echoes an appropriately formatted error message. When each <input> element is displayed, a call is made to the fieldError( ) function, as shown for the firstName and surname fields:
<tr>
<td><font color="red">First name:</font></td>
<td><? echo fieldError("firstName", $errors); ?>
<input type="text" name="firstName"
value="<? echo $formVars["firstName"]; ?>"
size=50></td>
</tr>
<tr>
<td><font color="red">Surname:</font></td>
<td><? echo fieldError("surname", $errors); ?>
<input type="text" name="surname"
value="<? echo $formVars["surname"]; ?>"
size=50></td>
</tr>
Figure 8-2 shows the final results: a client entry <form> with error messages placed over the corresponding fields.