The validate() function is defined in a separate file (for reasons that will become clear in
a moment), and it is more trivial PHP, as shown in Listing 7-6.
CHAPTER 7 n FORM VALIDATION AND JAVASCRIPT 161
Listing 7-6. validation.php contains the validation functions for each field
function validate($field, $value) {
switch ($field) {
case "dayofyear":
if (is_numeric($value) && intval($value) > 0 && intval($value) <= 365) {
return "";
} else {
return "Day of year must be between 1 and 365";
}
break;
case "date":
if (strtotime($value) === false) {
return "Invalid date (try 10 September 2000, +1 week, or next Thursday)";
} else {
return "";
}
break;
case "word":
if ($value == "" || is_numeric($value)) {
return "You must supply a favorite word";
} else {
return "";
}
break;
default:
return "";
}
}
You pass a field name and a field value to the validate() function. It returns an empty
string if the value is valid and an error message if it isn??™t. This function could obviously call
other functions and be as complex as you like.
The Client Side
The advantage of having the validation routine separate from the page is that you can then
enhance the form by having JavaScript check the validity of each field through an Ajax call
to the server. In simple terms, it should work like this:
CHAPTER 7 n FORM VALIDATION AND JAVASCRIPT 162
1. On page load, attach a handler to the blur event of each field.
Pages:
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236