Programmer to Programmer (TM)
www.asptoday.com
keyword search

ADSI/CDO (13)
ASP Tricks (84)
ASP+ (3)
BackOffice (32)
Components (69)
Data Access (117)
Miscellaneous (31)
Non-MS ASP (8)
Scripting (77)
Security/Admin (42)
Site Design (36)
Site server (13)
XML (54)
free email updates

ASPTODAY Diary
S M T W T F S
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
Links
Author Page
About ASPToday
Jun 29, 1999 
By Alexander Nakhimovsk
By Alexander Nakhimovsk
Scripting
Security/Admin
 
enter the discussion

A Library of Regular Expressions for Form Validation 

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.

HTML attributes and JavaScript object properties

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.

Regular Expressions for pattern matching

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

Libraries of Regular Expressions

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 well
 var 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:

Explanation of the validateForm function, and possible improvements

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:

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.

Click here to download this articles support material.


RATE THIS ARTICLE

Overall
Poor Excellent
User Level
Beginner Expert
Useful
No! Very
enter the discussion
 

Related Articles on ASPToday

Professional Form Validation
JScript Primer 3/4 : Regular Expressions
The ABC's of Scripting Technology
VBScript and JScript interactions within ASP pages
Advanced Client-Side Form Validation
Putting Remote Scripting to Work
Using JavaScript's OO Capabilities for Advanced Client-Side Validation

Related Links

Instant JavaScript
JavaScript Objects
Beginning Java 2
Professional ASP Techniques For Webmasters
Professional Active Server Pages 2.0


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.