HTML and CSS Reference
In-Depth Information
Let's start by adding the code to validate the age. Edit the formvalidation.html file to
add the following script block in the <head> section above the </head> tag:
<script type="text/javascript">
<!-- <![CDATA[
function validateForm()
{
if (document.forms[0].userAge.value < 18)
{
alert ("Age is less than 18. You are not an adult.");
return false;
} // end if
alert ("Age is valid.");
return true;
} // end function validateForm
// ]]> -->
</script>
The validateForm() function will check the age in the userAge input box. If it is less
than 18, the alert message will be displayed and a value of false will be returned and
the function will finish executing. The onsubmit event handler will become "return
false" and the form will not be submitted. If the age is 18 or greater, the statements in
the if structure will be skipped and the alert("Age is valid."); will execute. After
the user clicks the OK button in the alert message, the statement return true; will
execute and the onsubmit event handler will become "return true" ; thus, the form
will be submitted. Let's test this out!
Type a value less than 18 in the userAge input box and click the submit button. If the
form submits right away, there is likely an error in the JavaScript code. If this happens,
open the Error Console and correct the errors indicated. Figure 14.19 shows the input
in the Age box and the alert message displayed after clicking the submit button.
Figure 14.19
The
validateform.html file
displayed in the
browser with input
for age less than
18—notice the alert
message
Search WWH ::




Custom Search