9.7.1. ProblemYou want to make sure only valid checkboxes are checked. 9.7.2. SolutionFor 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 9-14 figures out whether a checkbox was checked, unchecked, or had an invalid value submitted. Validating a single checkbox
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, as shown in Example 9-15. Validating a group of checkboxes
9.7.3. DiscussionFor PHP to handle multiple checkbox values properly, the checkboxes' name attribute must end with [], as described in Recipe 9.17. Those multiple values are formatted in $_POST as an array. Since the checkbox name in Example 9-15 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 in Recipe 9.2 to determine that something was submitted for the checkbox before proceeding with further validation. 9.7.4. See AlsoRecipe 9.2 for information about validating required fields; documentation on array_intersect( ) at http://www.php.net/array_intersect. |