HTML and CSS Reference
In-Depth Information
11.5.1 Simple Form Validation
Have you ever filled out a form to buy something, clicked the submit button, waited,
waited, and then received a big red message saying that the card number you entered
was invalid? And then after all that waiting, you had to retype the entire form because
all of the fields were reset? By letting JavaScript do some preliminary checking of the
form input for obvious mistakes and erroneous information, you can save the user a
lot of time and aggravation. Then, after the preliminary checking is done, the form is
ready to go off to a server program, such as Perl or PHP, where it can be further vali-
dated and processed. This section will show you a little about validating forms: doing
preliminary checking to see if a password is the correct length, making sure a field isn't
empty, checking for unwanted characters, and more. Chapter 17, “Regular Expres-
sions and Pattern Matching,” shows you how to validate the format for e-mail
addresses, credit cards, zip codes, names, phone numbers, Social Security numbers,
and the like by using regular expressions, a powerful pattern matching tool provided
by JavaScript.
Checking for Empty Fields. Forms often have mandatory fields that must be filled
out before the form can be submitted. The following example checks for empty fields.
EXAMPLE 11.26
<html>
<head><title>An HTML Form and the onSubmit Event Handler</title>
<script type="text/javascript">
1
function checkForm(yourinfo){
2
if(yourinfo.namestring.value == "" ||
yourinfo.namestring.value == null){
// Check for an empty string or null value
3
alert("Please type in your name");
4
return(false);
}
else{
5
return(true);
}
}
</script>
</head>
<body>
<b>
6
<form name="info" action="http://cgi-bin/bookstuff/form1.cgi"
method="post"
7
onSubmit="return checkForm(this);" >
<big><p>
Continues
 
 
Search WWH ::




Custom Search