Validate Drop-Downs, Radio Buttons, and Check Boxes in the PHP - dummies

Validate Drop-Downs, Radio Buttons, and Check Boxes in the PHP

By Steve Suehring, Janet Valade

Validating web form data from drop-downs (or select/option elements), radio buttons, or check boxes should be done in the PHP. Even though it may appear that the users have to pick from one of the options, they may (maliciously or otherwise) not have that filled out correctly. It’s your job to make sure it’s valid.

The following code sets up an array of the valid states (from the drop-down in form.php) and then looks to see if what’s being received is found in that valid array. This code can be added just above the final disposition section.

validStates = array("Alabama","California","Colorado","Florida","Illinois","New Jersey","New 
if (isset($_POST['state']) && $_POST['state'] != ") {
    if (!in_array($_POST['state'],$validStates)) {
        $_SESSION['error'][] = "Please choose a valid state";

One item of note here is that you not only need to check to see if the state is set, but also need to see that it isn’t blank. You need to do this because the default value on the form is blank for this drop-down and the field isn’t required, so blank is a valid value. If it’s set and not blank, though, then it needs to be set to a valid value.

The set of phone number type radio buttons is the same concept. Set up an array of valid values and check to make sure the value passed in is one of those valid values. Since this field isn’t required unless the phone number is filled in, save its check for later.