14.9 Form Handling^561
Click the OK button and type an age that is 18 or greater in the userAgeinput box.
Click the submit button. Figure 14.20 shows the input in the userAgeinput box, the
alert message after the submit button has been clicked, and the resulting Web page after
the form has been submitted.
Now let’s add another ifstatement to validate the name. To ensure that something has
been entered in the userNameinput box, we will test to see if the value of the input box
is empty. The nullstring is represented by two double quotes, "",or two single quotes
", without a space or any other character in between. We can compare the value of the
userNametext box to the null string. If the value of the userNamebox is equal to the
nullstring, then we know that the user did not enter any information in this box. In
our example, we will be sending only one error message at a time. If the user does not
have a name in the userNamebox and also does not have an appropriate age in the
userAgebox, the user will only see the userNameerror appear. After the user corrects
the name and resubmits, the user will see the userAgeerror appear. This is very basic
form processing but it gives you an idea of how form handling might be accomplished.
More sophisticated form processing would verify each form field and indicate all errors
each time the form is submitted.
Let’s add the code to validate the userNamedata. Edit the script block as follows. Note
that two equals signs represent equivalent in the ifstatement. Some students find it
helpful to read the two equal signs (==) as “is exactly equal to.”
<script type="text/javascript">
<!-- <![CDATA[
function validateForm()
{
if (document.forms[0].userName.value == "" )
{
alert("Name field cannot be empty.");
return false;
} // end if
Figure 14.20
The
validateform.html file
displayed in the
browser with input
for age greater than
or equal to 18—
notice the alert
message; the
browser on the right
shows the resulting
Web page after the
form is submitted