Java Reference
In-Depth Information
Try It Out Form Validation Module
In this Try It Out, you'll create a set of useful JavaScript functions that use regular expressions to vali-
date the following:
Telephone numbers
Postal codes
E-mail addresses
The validation only checks the format. So, for example, it can't check that the telephone number actually
exists, only that it would be valid if it did.
First is the .js code fi le with the input validation code. Please note that the lines of code in the follow-
ing block are too wide for the topic — make sure each regular expression is contained on one line.
function isValidTelephoneNumber( telephoneNumber )
{
var telRegExp = /^(\+\d{1,3} ?)?(\(\d{1,5}\)|\d{1,5}) ?\d{3}
?\d{0,7}( (x|xtn|ext|extn|pax|pbx|extension)?\.? ?\d{2-5})?$/i
return telRegExp.test( telephoneNumber );
}
function isValidPostalCode( postalCode )
{
var pcodeRegExp = /^(\d{5}(-\d{4})?|([a-z][a-z]?\d\d?|[a-z{2}\d[a-z])
?\d[a-z][a-z])$/i
return pcodeRegExp.test( postalCode );
}
function isValidEmail( emailAddress )
{
var emailRegExp = /^(([^<>()\[\]\\.,;:@“\x00-\x20\x7F]|\\.)+|(“”“
([^\x0A\x0D”\\]|\\\\)+”“”))@(([a-z]|#\d+?)([a-z0-9-]|#\d+?)*
([a-z0-9]|#\d+?)\.)+([a-z]{2,4})$/i
return emailRegExp.test( emailAddress );
}
Save this as ch9_examp7_module.js.
To test the code, you need a simple page with a text box and three buttons that validate the telephone
number, postal code, or e-mail address.
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>example 7</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8” />
<script type=”text/javascript” src=”ch9_examp7_module.js”></script>
</head>
<body>
<form name=”form1”>
<p>
<label>
Search WWH ::




Custom Search