2 If the value in the first text field is an empty string represents a string with no text or null represents no value, the user is sent an alert asking him or her to fill in his or her
Trang 117.5 Form Validation with Regular Expressions
When you fill out a form on the Web, you are typically asked for your name, phone
number, address (a popup menu of all the states is usually provided), and then all sorts
of credit card information Sometimes it takes four or five tries to get it right because you
didn’t complete the form exactly the way you were asked A message will appear and you
won’t be allowed to submit the form until you get it right Behind the scenes a JavaScript
program is validating the form
17.5.1 Checking for Empty Fields
There’s a form waiting to be filled out Some of the fields are optional, and some are
man-datory The question is this: Did the user fill in the mandatory fields? If he or she didn’t,
the form can’t be processed properly Checking for empty or null fields is one of the first
things you might want to do
Figure 17.37 Subpatterns are used in string replacement.
E X A M P L E 1 7 3 6
<html>
<head><title>Checking for Empty Fields</title>
<script type="text/javascript">
1 function validate_text(form1) {
2 if ( form1.user_name.value == "" ||
form1.user_name.value == null){
alert("You must enter your name.");
return false;
}
3 if ( form1.user_phone.value == "" ||
form1.user_phone.value == null){
alert("You must enter your phone.");
return false;
}
Trang 2onSubmit="return validate_text(formtest)">
Please enter your name: <br />
6 <input type="text" size=50 name="user_name" />
<p>
Please enter your phone number: <br />
7 <input type="text" size=30 name="user_phone" />
</p><p>
<input type=submit value="Send">
<input type=reset value="Clear">
</p>
</form>
</body>
</html>
E X P L A N A T I O N
1 A user-defined function called validate_text() is defined It takes one parameter, a
reference to a form
2 If the value in the first text field is an empty string (represents a string with no
text) or null (represents no value), the user is sent an alert asking him or her to
fill in his or her name If a false value is returned, the form is not submitted.
3 If the value in the second text field is an empty string or null, the user is sent an
alert asking him or her to fill in a phone number If a false value is returned, the
form is not submitted
4 If both text boxes were filled out, a true value is returned, and the form will be
submitted to the server’s CGI program whose URL is listed in the action attribute
of the form
5 The onSubmit event is triggered when the user clicks the submit button The
han-dler function, validate_text(), will be called with a reference to this form.
6 The input type for this form is a text box that will get the name of the user
7 Another text box is created to hold the phone number of the user See
Figure 17.38
Trang 317.5.2 Checking for Numeric Zip Codes
If you ask the user for a five-digit zip code, it is easy to check using a regular expression
by matching for exactly five digits:
/^\d{5}$/
Here is another way to say the same thing:
/^[0-9][0-9][0-9][0-9][0-9]$/
Some longer zip codes contain a dash followed by four numbers This long zip code
format could be represented as:
/^\d{5}-?\d{4}$/
The beginning and end of line anchors prevent the matched string from containing any
extraneous characters at either end of the string See Example 17.37
Figure 17.38 The user left the phone number field empty, so the form was not
submitted.
E X A M P L E 1 7 3 7
<html>
<head><title>Testing for a Valid Zip Code</title>
<script type="text/javascript">
1 function ok_Zip(zip){
alert("Zip code must contain exactly five numbers!");
zip.focus();
return false;
}
Trang 4<big>
<form name="ZipTest" action="/error" >
Enter your zip code:
<input type="text"
name="zipcode"
size=5 />
<input type="button"
value="Check zip"
5 onClick="if( ok_Zip(ZipTest.zipcode)) {
alert('Zip is valid.')}" />
<br /><input type="reset">
</form>
</big>
</body>
</html>
E X P L A N A T I O N
1 The function, called ok_Zip(), is defined to validate the zip code entered by the user
2 The regular expression reads: Look for exactly five digits The beginning of line
and end of line anchors ensure that there will not be any extraneous characters
before or after the five digits
3 The regular expression test() method checks that the value entered by the user is
a valid zip code If not, an alert dialog box will tell the user, focus will be returned
to the text box, and false will be returned.
4 If the user doesn’t enter anything, an alert dialog box will appear, focus will be
re-turned to the text box, and false will be rere-turned.
5 The onClick event is triggered when the user clicks the Check zip button A
Java-Script statement to call the ok_Zip() function is assigned to the event If the user
en-tered a valid zip code, the alert dialog box will pop up and say so See Figure 17.39
Trang 517.5.3 Checking for Alphabetic Data
To test for entries that must consist strictly of alphabetic input, such as a name, state, or
country field, the regular expression character set can be used; for example, /[a-zA-z]+/
is a regular expression that matches a string containing one or more uppercase or
low-ercase letters, and /^[a-zA-Z]+$/ matches a string containing only one or more
upper-case or lowerupper-case letters, because the character set is enclosed within the beginning
and ending anchor metacharacters To represent one or more alphanumeric word
characters, [A-Za-z0-9_], you can use the \w metasymbol; for example, /\w+/ represents
one or more alphanumeric word characters
Figure 17.39 The user enters a five-digit zip code (top); the user enters nothing
(middle); the user enters four digits and one letter (bottom).
Trang 6}
3 if ( form.fname.value == ""){
alert("You must enter your first name.");
form.fname.focus();
return false;
}
}
</script>
</head>
<body>
<big>
5 <form name="alphaTest"
method="post"
action="/cgi-bin/testing.pl"
6 onSubmit="return okAlpha(this)" />
Enter your first name:
<input type="text"
size=20 />
<p>
8 <input type="submit" value="Submit" />
<input type="reset" />
</form>
</big>
</body>
</html>
E X P L A N A T I O N
1 A function called okAlpha() is defined It takes one parameter, a reference to a form.
Its purpose is to make sure the user entered only alphabetic characters in the form
2 A regular expression is created It reads: Starting at the beginning of the line, find
one or more uppercase or lowercase letters in the character class [A-Za-z]
fol-lowed by the end of line anchor ($) The regular expression is tested against the
input that came in from a text box named text If it doesn’t match, the alert box
will notify the user, and false is returned to the onSubmit handler on line 6 The
Trang 717.5.4 Removing Extraneous Characters
Removing Spaces and Dashes. To remove any unwanted spaces or dashes from
user input, the String object’s replace() method can be used to find the characters and
replace them with nothing, as shown in Example 17.39
3 If the user didn’t enter anything at all and the field is empty, another alert will be
sent to the user, and false will be returned The form will not be submitted.
4 If the user entered only alphabetic characters in his or her name, true will be
re-turned, and the form will be submitted
5 This is where the HTML form starts
6 The onSubmit handler will be triggered when the user clicks the Submit button,
and the okAlpha() function will be called, passing a reference to the form called
alphaTest.
7 The user enters his or her name in the text field called fname.
8 After filling out the form, the user will click the Submit button, thereby triggering
the onSubmit handler on line 6 See Figure 17.40.
Figure 17.40 The user has a digit in her name She can only enter alphabetic
characters, or she will see the warning.
E X A M P L E 1 7 3 9
<html>
<head><title>Removing Spaces and Dashes</title></head>
<body bgcolor="magenta">
<big>
<h2>Removing Spaces and Hyphens</h2>
<script type= "text/javascript">
1 var string="444- 33 - 12 34"
2 var regex = /[ -]+/g;
3 var newString=string.replace(regex, "");
document.write("The original string: "+string);