|
The meat of the form validation script is in the validate_form() function. This function takes a single parameter (a reference to the superglobal array to validate). When executed, this function attempts to perform a number of tasks in the interest of validating the data. During the course of this function, if any validation errors occur, validate_form() calls the add_error() function with an appropriate error message (hence populating the error variables). When executed, the validate_form() starts by first processing the required hidden field and checks to make sure that all required fields are not empty. Following this check, the validate_form() attempts to process each individual form element according to the following rules:
-
If the element is named submit, required, or ends in _desc, it is ignored.
-
For all other elements, validate_form() attempts to call the function <name>_validate() (where <name> is the name of the current element).
Unless defined by the user, the <name>_validate() functions do not exist. These functions are your responsibility to create to validate each individual form element (or at least the elements you are concerned with validating). These functions should accept two parameters (the value submitted and a description of the field taken from the <name>_desc element) and should return true if the submitted value is valid or return an error message upon failure. For example, if you were validating a form element whose NAME attribute is phone (a phone number), the following function should be defined to validate that data (see ):
Listing 5.9. A Sample Form Element Validation Function
<?php function phone_validate($data, $desc) { $regex = "/^\([2-9][0-9]{2}\)[2-9][0-9]{2}-[0-9]{4}/i"; if(preg_match($regex, $data) != 1) { return "The '$desc' field isn't valid!"; } return true; } ?>
Assuming that each validate_form() executes and does not encounter any errors, it then calls the _process_form() function. This function is designed to clean up any nonrequired form elements (the _desc, submit, and required hidden elements) and call the function process_form(). As with the validation functions just discussed, the process_form() function must be defined by you and is designed to allow you to actually perform whatever action was desired after a successful validation. It accepts a single parameter (an array of the submitted data) and has no return value. If this function does not exist, nothing will be done with the submitted data upon a successful validation. A sample process_form() function is provided in , which emails the contents of the form:
|