How to Create a Validation Function for a Web Page Form

The filter_var function goes a long way toward providing automated validation for common form elements. If you start working with forms, you'll find that you need to validate the same things over and over again, like ZIP code or state, too. Unfortunately, there aren't any built-in PHP functions to validate a ZIP code or state. But there's nothing preventing you from creating one!

function is_valid_state($state) {
    $validStates = array("Alabama","California","Colorado","Florida","Illinois","New Jersey","New York","Wisconsin");
    if (in_array($state,$validStates)) {
        return true;
    } else {
        return false;
    }
} //end function is_valid_state

This function accepts an argument of the state to check. The state is checked against the list of known states. If the state is found among that list, the function returns Boolean true, meaning that it's a valid state.

function is_valid_zip($zip) {
        if (preg_match('/^[d]+$/',$zip)) {
                return true;
        } else if (strlen($zip) == 5 || strlen($zip) == 9) {
                return true;
        } else {
                return false;
        }
} //end function is_valid_zip

Like the state function, the ZIP function also accepts an incoming argument, this time the ZIP code to validate. The same basic validation checks are performed in this function as they were in the non-functionalized version from the form-process.php file. If the ZIP is just digits and is either five or nine digits, then Boolean true is returned; otherwise, false is returned.

In most cases, you'd create these functions in an external file and then require that file wherever needed through require_once() or through your autoload process. For example, you included those validation functions in a file called validation.inc and then used the following line at the top of the form-process.php file.

require_once("validation.inc");

Changing the form-process.php file to use these functions looks like this:

if (isset($_POST['state']) && $_POST['state'] != "") {
    if (!is_valid_state($_POST['state'])) {
        $_SESSION['error'][] = "Please choose a valid state";
    }
}
 
if (isset($_POST['zip']) && $_POST['zip'] != "") {
    if (!is_valid_zip($_POST['zip'])) {
        $_SESSION['error'][] = "ZIP code error.";
    }
}
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com