Recipe 9.6. Validating Form Input: Radio Buttons

9.6.1. Problem

You want to make sure a valid radio button is selected from a group of radio buttons.

9.6.2. Solution

Use an array of values to generate the menu. Then validate the input by checking that the submitted value is in the array. Example 9-13 uses array_key_exists( ) to do the validation.

Validating a radio button

<?php // Generating the radio buttons $choices = array('eggs' => 'Eggs Benedict',                  'toast' => 'Buttered Toast with Jam',                  'coffee' => 'Piping Hot Coffee'); foreach ($choices as $key => $choice) {    echo "<input type='radio' name='food' value='$key'/> $choice \n"; } // Then, later, validating the radio button submission if (! array_key_exists($_POST['food'], $choices)) {     echo "You must select a valid choice."; } ?>

9.6.3. Discussion

The radio button validation in Example 9-13 is very similar to the drop-down menu validation in Example 9-12. They both follow the same pattern'define the data that describes the choices, generate the appropriate HTML, and then use the defined data to ensure that a valid value was submitted. The difference is in what HTML is generated.

Another difference between drop-down menus and radio buttons is how defaults are handled. When the HTML doesn't explicitly specify a default choice for a drop-down menu, the first choice in the menu is used. However, when the HTML doesn't explicitly specify a default choice for a set of radio buttons, no choice is used as a default.

To ensure that one of a set of radio buttons is chosen in a well-behaved web browser, give the default choice a checked="checked" attribute. In addition, to guard against missing values in hand-crafted malicious requests, use isset( ) to ensure that something was submitted for the radio button, as described in Recipe 9.2.

9.6.4. See Also

Recipe 9.2 for information on validating required fields; documentation on array_key_exists( ) at

PHP Cookbook, 2nd Edition
PHP Cookbook: Solutions and Examples for PHP Programmers
ISBN: 0596101015
EAN: 2147483647
Year: 2006
Pages: 445

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: