PHP Forms
Validating Form Input: Checkboxes
Problem
You want to make sure only valid checkboxes are checked.
Solution
For a single checkbox, ensure that if a value is supplied, it’s the correct one. If a value isn’t supplied for the checkbox, then the box wasn’t checked.
Example Validating a single checkbox
// Generating the checkbox
$value = 'yes';
echo "<input type='checkbox' name='subscribe' value='yes'/> Subscribe?";
// Then, later, validating the checkbox
if (filter_has_var(INPUT_POST, 'subscribe')) {
// A value was submitted and it's the right one
if ($_POST['subscribe'] == $value) {
$subscribed = true;
} else {
// A value was submitted and it's the wrong one
$subscribed = false;
print 'Invalid checkbox value submitted.';
}
} else {
// No value was submitted
$subscribed = false;
}
if ($subscribed) {
print 'You are subscribed.';
} else {
print 'You are not subscribed';
}
For a group of checkboxes, use an array of values to generate the checkboxes. Then, use array_intersect() to ensure that the set of submitted values is contained within the set of acceptable values.
Example Validating a group of checkboxes
// Generating the checkboxes
$choices = array('eggs' => 'Eggs Benedict',
'toast' => 'Buttered Toast with Jam',
'coffee' => 'Piping Hot Coffee');
foreach ($choices as $key => $choice) {
echo "<input type='checkbox' name='food[]' value='$key'/> $choice \n";
}
// Then, later, validating the radio button submission
if (array_intersect($_POST['food'], array_keys($choices)) != $_POST['food']) {
echo "You must select only valid choices.";
}
Discussion
For PHP to handle multiple checkbox values properly, the checkboxes’ name attribute must end with []. Those multiple values are formatted in $_POST as an array. Since the checkbox name is food[], $_POST['food'] holds the array of values from the checked boxes.
The array_intersect() function finds all of the elements in $_POST['food'] that are also in array_keys($choices). That is, it filters the submitted choices ($_POST['food']), only allowing through values that are acceptable—keys in the $choices array. If all of the values in $_POST['food'] are acceptable, then the result of array_intersect($_POST['food'], array_keys($choices)) is an unmodified copy of $_POST['food']. So if the result isn’t equal to $_POST['food'], something invalid was submitted.
Checkboxes have the same issues with default values as do radio buttons. So just as with radio buttons, use the rules to determine that something was submitted for the checkbox before proceeding with further validation.
No comments:
Post a Comment