HTML and CSS Reference
In-Depth Information
array with the name of the field as the key and the error message as the array value.
Later on, I display the error messages and use the field names to mark the fields that
have errors.
On the first line of the function, I declare
$errors
to store the errors found during vali-
dation. Next, I validate the
name
parameter. PHP has a built-in function called
empty()
that checks to see whether a variable is empty. In this case, I use it to check
$_POST['name']
, which was set automatically when the form was submitted. If that vari-
able is empty, meaning that the user did not submit his or her name, I add an entry to
$errors
.
Next, I validate the
age
field using PHP's
is_numeric()
function. I negate the condition
with the not operator because it's only an error if the value in the field isn't a number.
Finally, I check to make sure that the user has selected a toy. As you saw, this field is
actually a check box group, meaning that the contents of the field are submitted as an
array (assuming I've named the field properly). Again, I use
empty()
here. It works with
regular variables and arrays, and it returns true if an array contains no elements. If there
are no elements in the array, no toys were submitted, and the error is added to the array.
When validation is complete, I return the value of the
$errors
variable to the caller.
Here's the code I use to call the
validate()
function. It lives right at the top of the page:
$errors = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$errors = validate();
}
I check on
$errors
later in the page regardless of whether I validate the input, so I go
ahead and declare it. To determine whether I should validate a form submission or dis-
play an empty form, I check the built-in variable
$_SERVER['REQUEST_METHOD']
to see
whether the request was submitted using the
POST
method. If it was, I want to do the
input validation. If not, I just want to display the form.
If any parameters were submitted via
POST
, I run the
validate()
function I just
described. There's one more line of code at the top of the page where most of my PHP
code lives:
$toys = array('digicam' => 'Digital Camera',
'mp3' => 'MP3 Player', 'wlan' => 'Wireless LAN');
21
It's an array that contains a list of all the check boxes to display for the
toys
field. It's
easier to iterate over all the check boxes in a loop than it is to code them all by hand. If I

