Try
It Out - A Simple Form with Validation
Let's
put all the above information on text boxes and buttons together into an example.
In this example we have a simple form consisting of two text boxes and a button.
The top text box is for the user's name, the second for their age. We do various
validity checks. We check the validity of the age text box when it loses focus.
However, the name and age text boxes are only checked to see if they are empty
when the button is clicked.
<HTML> <HEAD> <SCRIPT
LANGUAGE=JavaScript> function butCheckForm_onclick() { var
myForm = document.form1; if (myForm.txtAge.value == "" || myForm.txtName.value
== "") { alert("Please complete all the form");
if (myForm.txtName.value == "") {
myForm.txtName.focus(); } else {
myForm.txtAge.focus(); } } else {
alert("Thanks for completing the form " + myForm.txtName.value);
} } function txtAge_onblur() { var txtAge = document.form1.txtAge;
if (isNaN(txtAge.value) == true) { alert("Please
enter a valid age"); txtAge.focus(); txtAge.select();
} } function txtName_onchange() { window.status
= "Hi " + document.form1.txtName.value; } </SCRIPT>
</HEAD> <BODY> <FORM NAME=form1> Please
enter the following details: <P> Name: <BR>
<INPUT TYPE="text" NAME=txtName onchange="txtName_onchange()">
<BR> Age: <BR> <INPUT TYPE="text"
NAME=txtAge onblur="txtAge_onblur()" SIZE=3 MAXLENGTH=3>
<BR> <INPUT TYPE="button" VALUE="Check Details"
NAME=butCheckForm onclick="butCheckForm_onclick()">
</FORM> </BODY> </HTML> |
After you've entered the text,
save the file as ch6_examp4.htm and load it into your web browser.
Type
your name into the name text box. When you leave the text box you'll see Hi yourname
appear in the status bar at the bottom of the window.
Enter
an invalid value into the age text box, such as 'aaaa', and when you try to leave
the box it'll tell you of the error and send you back to correct it.
Finally
click the Check Details button and both text boxes will be checked to see that
you have completed them. If either is empty, you'll get a message telling you
to complete the whole form and it'll send you back to the box that's empty.
If
everything is filled in correctly, you'll get a message thanking you.
Note
that, at the time of writing, this example does not work properly on NN 6.