Page 214 - Open Soource Technologies 304.indd
P. 214
Web Technologies-I
Notes $varMovie = $_POST[‘formMovie’];
$varName = $_POST[‘formName’];
$varGender = $_POST[‘formGender’];
$errorMessage = “”;
// - - - snip - - -
}
?>
Select box input is accessed just like a text box. Now let’s put in some validation.
9.4.3 Validating the Form Data
It is always a good idea to have a “blank” option as the first option in your select box. It forces
the user to make a conscious selection from the box and avoids a situation where the user might
skip over the box without meaning to. Of course, this requires validation.
<?php
if(empty($varMovie)) {
$errorMessage .= “<li>You forgot to enter a movie!</li>”;
}
if(empty($varName)) {
$errorMessage .= “<li>You forgot to enter a name!</li>”;
}
if(empty($varGender)) {
$errorMessage .= “<li>You forgot to select your Gender!</li>”;
}
?>
(For a generic, easy to use form validation script, see PHP Form Validation Script)
It is also a good idea to put your validation checks in the same order as the inputs appear on
the form. This way, if there are multiple errors, correcting them will be easier for the user. One
other missing piece is that, as before, we want to preserve the user’s choice in the select box,
just in case there’s a validation error in one of the other fields.
Here is how to do that:
<p>
Please choose your gender
<select name=”formGender”>
<option value=””>Select...</option>
<option value=”M”
<? if($varGender==”M”) echo(“ selected=\”selected\””);?> >Male
</option>
208 LOVELY PROFESSIONAL UNIVERSITY