Validating Multiple-Choice Input
Checkboxes and drop-down lists are an important component of web forms, and it's often necessary to include validation for these controls in your PHP applications. Normally, the user's selections from these controls are submitted to the form processor in the form of an array, and it's necessary to use PHP's array functions to validate them.
To see this in action, consider the following script, which requires the user to fill out a brief user profile and select at least three hobbies and two subscriptions from the multiple-choice controls presented.
<basefont face="Arial">
// form not submitted
form action="<? = $_SERVER['PHP_SELF']?>" method="post"> Username:
<input type="text" name="username"> <p />
<input type="password" name="password"> <p />
Date of Birth:
Month <input type="text" name="month" size="2"> Day <input type="text" name="day" size="2">
Year <input type="text" name="year" size="4">
Hobbies (select at least <b>three</b>): <br />
<input type="checkbox" name="hobbies[] <input type="checkbox" name="hobbies[] <input type="checkbox" name="hobbies[] <input type="checkbox" name="hobbies[]
<input type="checkbox" name="hobbies[] <p />
Subscriptions (Select at least <b>two</b>):
value="Sports">Sports value="Reading">Reading value="Travel">Travel value="Television">Television value="Cooking">Cooking
<select name="subscriptions[]" multiple> <option value="General">General Newsletter</option> <option value="Members">Members Newsletter</option> <option value="Premium">Premium Newsletter</option>
<input type="submit" name="submit" value="Sign Up"> </form>
// form submitted
// validate "username", "password" and "date of birth" fields $username = (!isset($_POST['username']) || J trim($_POST['username']) == "") J
? die ('ERROR: Enter a username') : trim($_POST['username']);
$password = (!isset($_POST['password']) J || trim($_POST['password'] == "")) J
? die ('ERROR: Enter a password') : trim($_POST['password']);
if (!checkdate($_POST['month'], $_POST['day'], $_POST['year'])) {
// check the "hobbies" field for valid values $hobbies = ((sizeof($_POST['hobbies']) < 3) ? J die ('ERROR: Please select at least 3 hobbies') : J implode(',', $_POST['hobbies']));
// check the "subscriptions" field for valid values $subscriptions = ((sizeof($_POST['subscriptions']) < 2) ? J die ('ERROR: Please select at least 2 subscriptions') : J implode(',', $_POST['subscriptions']));
// connect to database // save record
Now, try submitting the form without first selecting the required number of items from each multiple-choice control, and you will be presented with an error message.
The options selected by a user from each multiple-choice control are submitted in the form of a PHP array. Thus, it is convenient to use PHP's array functions—namely, the sizeof() function, which returns the number of elements in an array—to check whether the required number of options was selected.
Post a comment