HTML and CSS Reference
In-Depth Information
EXAMPLE 17.38
<html>
<head><title>Testing for Alphabetic Characters</title>
<script type="text/javascript">
1
function okAlpha(form) {
2
var regex=/^[a-zA-Z]+$/;
// Match for upper- or lowercase letters
if ( regex.test(form.fname.value) == false) {
alert("First name must contain alphabetic characters!");
form.fname.focus();
return false;
}
3
if ( form.fname.value == ""){
alert("You must enter your first name.");
form.fname.focus();
return false;
}
4
return true;
}
</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"
7
name="fname"
size=20 />
<p>
8
<input type="submit" value="Submit" />
<input type="reset" />
</form>
</big>
</body>
</html>
EXPLANATION
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
form will not be submitted.
Search WWH ::




Custom Search