PHP Forms
Validating Form Input: Radio Buttons
Problem
You want to make sure a valid radio button is selected from a group of radio buttons.
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 Validating a radio button
// 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.";
}
Discussion
The radio button validation is very similar to the drop-down menu validation. 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.
One 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 the following code, toast is the default:
// Defaults
$defaults['food'] = 'toast';
// 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'";
if ($key == $defaults['food']) {
echo ' checked="checked"';
}
echo "/> $choice \n";
}
// Then, later, validating the radio button submission
if (! array_key_exists($_POST['food'], $choices)) {
echo "You must select a valid choice.";
}
In addition, to guard against missing values in hand-crafted malicious requests, use filter_has_var() to ensure that something was submitted for the radio button.
No comments:
Post a Comment