| Programmer to Programmer (TM) |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||||||||||||||||||||||
| ||||||||||||||||||||||||||||||||||||||||||||||||||||
| Links Author Page About ASPToday | ||||||||||||||||||||||||||||||||||||||||||||||||||||
| |
| Home | Today's Article | Search | Feedback | Write For Us | Suggest an Article | Advertise | |
| Jun 29, 1999 |
|
| By Alexander Nakhimovsk |
| Scripting |
| Security/Admin |
| enter the discussion |
JavaScript is fast becoming the scripting language of choice - its compatibility with object oriented programming and links with Internet technologies demand that this language be taken seriously. With the greater level of sophistication required of web pages, the need for reusable, easily maintainable, independent objects is growing. One example of advanced JavaScript programming is the library of Regular Expressions for form validation, of which fuller discussion can be found in the Wrox Press book, JavaScript Objects co-authored by Tom Myers and myself
Regular Expressions constitute a relatively small programming language embedded within a host. They were introduced into JavaScript as a fourth generation browser feature, where they serve as powerful tools for pattern matching and other string evaluation and processing tasks. They are especially invaluable when used to analyse a string input from a user - the data entered into forms on a web page, for example.
In this article I'll be showing you how easy it is to create a library of Regular Expressions that can be implemented in any of your web pages. By saving the form validation code in a file, you can avoid the trouble of re-writing the same piece of code over and over again, simply by including that file in all your HTML code.
As you probably know, you can add your own customized attributes to HTML
elements. For instance, if you have a form with a text-input element in it, you
can give it an attribute called validator:
<form id="exampleForm">
<input type="text" name="input1" validator="whatsThisFor?">
...
</form>
The attribute will be ignored by the rendering engine of the browser, and won't have any impact at all on how the page is displayed. Like the "real" attributes, however, this attribute will be exposed to the scripting language, and so it is possible to refer to it in JavaScript and to examine its value. The rules for referring to elements are, of course, different in IE4 and N4: although these examples will only work in IE4 or later, the same principles apply to Netscape pages:
if(document.all.exampleForm.input1.validator=="whatsThisFor")
alert("Oh, I dunno");else ...
If the attribute has not been defined, then an attempt to refer to it will return null, which evaluates to false in the context of the 'if' expression:
if(!document.all.exampleForm.input1.validator)
alert("No validator!");
Let's see how we can use these circumstances in form validation.
Much of form validation consists of pattern matching. To validate an input field for the postal (zip) code, for instance, you might want to make sure that the value either has five characters, all of them digits, or ten characters: five digits, a hyphen, and another four digits. You could write a function to check for these conditions, but it's easier to simply test the value against a regular expression pattern:
/\d{5}(-\d{4})?/
Regular Expressions, in case you've never used them before, form a language
for specifying patterns of characters. The main operation is matching. Most
characters simply match themselves: the regular expression /abc/
matches only the string "abc". However, there are ways to refer to classes of
characters (such as digits), and to specify how many of them should be matched.
In the pattern above:
\d{5} matches any five digits
-\d{4} matches a hyphen followed by four digits
? says that the last element of the pattern is optional, and may
or may not be there
You can start collecting Regular Expressions for various common form elements in a file, for instance:
var PatternsDict = new Object();
PatternsDict.zipPat = /^\d{5}(-\d{4})?$/;// matches zip codes
PatternsDict.currencyPat = /^\$\d{1,3}(,\d{3})*\.\d{2}$/;// matches $17.23 or $14,281,545.45 or ...
PatternsDict.timePat = /^\d{2}:\d{2}$/;// matches 12:34 but also 75:83
PatternsDict.timePat2=/^([1-9]|1[0-2]):[0-5]\d$/;
// matches 5:04 or 12:34 but not 75:83
The file should also contain this function:
function validateForm(theForm){// return true if all is wellvar elArr = theForm.elements; // get all elements of the form into array
for(var i = 0; i < elArr.length; i++)
with(elArr[i]){ // for each element of the form...var v = elArr[i].validator; // get validator, if any
if(!v) continue; // no validator property, skip
var thePat = PatternsDict[v]; // select the validating regular expr
var gotIt = thePat.exec(value); // run it on value of elArr[i]
if(!gotIt){alert(name + ": failure to match " + v + " to " + value); return false;}
} return true;
}
Let's say you call your file of validating patterns
valPatterns.js. Include that file in every page that has a form you
need to validate. All that's left to do is give an appropriate validator
attribute to your input boxes, as in this complete example:
<HTML> <HEAD>
<TITLE> formVal.HTM </TITLE>
<SCRIPT src=" ValPatterns.js">
/* file with patterns and the validateForm() function */
</SCRIPT>
<SCRIPT>
function showForm(theForm){ alert("hi, this is the form " + theForm.id + "\nperforming its Action");}
</SCRIPT> </HEAD>
<BODY> <P>This is a simple exercise in form validation.</P>
<FORM id = theForm onSubmit = "return validateForm(theForm)"
Action = "javascript:showForm(theForm)">
A zip code:
<INPUT TYPE=TEXT name=zip value="12345-6789" validator=zipPat> <BR>
Some currency:
<INPUT TYPE=TEXT name=money value="$12,345.90" validator=currencyPat> <BR>
A point in time:
<INPUT TYPE=TEXT name=time value="12:45" validator=timePat2> <BR>
Click to submit:
<INPUT TYPE = SUBMIT>
</FORM>
</BODY> </HTML>
This code should generate the following page, where the alert box shows when the Submit Query button is pressed and all the boxes contain correctly formatted strings:

The function goes through the elements of the form checking for the
validator property. When it comes to an element doesn't have it,
the scripts skips to the beginning of the loop and continues. If the property is
there, then the corresponding regular pattern is looked up in the patterns
dictionary PatternDict. Every regular expression has a
corresponding RegExp object. RegExp objects have an
exec() method that returns null if the argument does not match the
pattern with which the RegExp object is associated - in these
circumstances the alert box pops up.
There are several ways in which the entire validation process can be improved using JavaScript:
RegExp
constructor.
So you see, JavaScript really is an exciting development in client-side scripting languages, and I urge readers to spend some serious time considering its many potential uses.
| enter the discussion |
If you would like to contribute to ASPToday, then please get in
touch with us by clicking here.
ASPToday is a
subsidiary website of WROX Press Ltd.
Please visit their website. This article is copyright ©2000 Wrox Press Ltd.
All rights reserved.