Previous Example-|-Next Example-|-Return to Chapter Listing

Example 12.8:
onsubmit: Form Validation


This form uses the onsubmit event handler to verify the form entry. Note, however, that if you enter something beginning with text instead of a number, you'll get an error message. Or if you enter a number followed by text, the text is ignored. We'll see how to fix those problems later.
Type your age (you must be 18 or over):



These are the scripts we used. First, in the HEAD: <SCRIPT LANGUAGE="JavaScript"> <!-- function testAge() { var nAge = document.age.ageBox.value; if (nAge >= 18) { if (nAge >=100) { alert("You entered an age of " + nAge +". Enter an age from 18 to 99.") return false } else { return true } } else { alert("You entered an age of " + nAge + ". You must be 18 or over to use this service!") return false } } //--> </SCRIPT> Then we created this form: <FORM NAME="age" onsubmit="return testAge()"> Type your age (you must be 18 or over): <BR> <INPUT TYPE="text" NAME="ageBox"><P> <INPUT TYPE="Submit" NAME="Submit"> </FORM>
Previous Example-|-Next Example-|-Return to Chapter Listing