HTML and CSS Reference
Click the OK button and type an age that is 18 or greater in the userAge input box.
Click the submit button. Figure 14.20 shows the input in the userAge input box, the
alert message after the submit button has been clicked, and the resulting Web page after
the form has been submitted.
displayed in the
browser with input
for age greater than
or equal to 18—
notice the alert
browser on the right
shows the resulting
Web page after the
form is submitted
Now let's add another if statement to validate the name. To ensure that something has
been entered in the userName input box, we will test to see if the value of the input box
is empty. The null string 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
userName text box to the null string. If the value of the userName box is equal to the
null string, 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 userName box and also does not have an appropriate age in the
userAge box, the user will only see the userName error appear. After the user corrects
the name and resubmits, the user will see the userAge error 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 userName data. Edit the script block as follows. Note
that two equals signs represent equivalent in the if statement. Some students find it
helpful to read the two equal signs ( == ) as “is exactly equal to.”
if (document.forms.userName.value == "" )
alert("Name field cannot be empty.");
} // end if