Section 7.5. Input Fields and JiT Regular Expressions


7.5. Input Fields and JiT Regular Expressions

Most form fields just require some text without giving any concern to the format. However, certain types of fields may require a specific format. Rather than send the data across to the server to see if the data is valid, we'll use regular expressions to validate the format of the data, at a minimum, first.

Using regular expressions, as defined in Chapter 3, some of the more common validations are with the following fields:

  • Warranty or purchase certificates

  • Email addresses

  • Phone numbers

  • Social Security numbers or other forms of identification

  • Dates

  • State abbreviations

  • Credit card numbers

  • Web page URLs or other forms of URI (uniform resource identifiers)

Rather than try out various regular expressions directly in code, Example 7-5 contains a little application, the JiT RegEx Machine, that takes a regular expression typed in one field, a string in another, and then does a pattern match when the form is submitted. The results are output to a third field.

Example 7-5. The JiT RegEx Machine application

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>The JiT RegEx Machine</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript"> //<![CDATA[ if (window.addEventListener) {       window.addEventListener("load",setupEvents,false);    } else if (window.attachEvent) {       window.attachEvent("onload", setupEvents);    } else {       window.onload=setupEvents; } function setupEvents(evnt) {    document.someForm.onsubmit=validateField; } function validateField(evnt) {      var rgEx = new RegExp(document.someForm.text1.value);   var OK = rgEx.exec(document.someForm.text2.value);   // result and print out   if (!OK) {      document.someForm.text3.value = "Not a match";   } else {      document.someForm.text3.value = "The Pattern matched!";   }   return false; } //]]> </script> </head> <body> <form name="someForm" style="padding: 10px"> Regular Expression: <input type="text" name="text1" /><br /><br /> <textarea name="text2" cols=50 rows=10></textarea><br /> Result: <input type="text" name="text3" /><br /><br /> <input type="submit" value="Check RegExp" /> </form> </body> </html> 

Certificates of purchase and warranty numbers may have a pattern that requires certain letters and/or numbers to appear in certain positions. As an example, if you have a certificate identifier that is 13 characters long, with the characters BUS in the sixth through eighth position, and alphanumeric characters in the remaining spots, you might try the following regular expression:

^\w{5}BUS\w{5}

If you're validating an email address, which requires an amphora (at symbol), some form of domain, and little other restriction, the following should work:

^.+@[^\.].*\.[a-z]{2,}$

As for date, the following could work if you want a date in the format mm/dd/yyyy:

^\d{2}\/+\d{2}\/+\d{4}

Examples too simple so far? Well, check out the following for Social Security numbers:

^(?!000)([0-6]\d{2}|7([0-6]\d|7[012]))([ -]?)(?!00)\d\d\3(?!0000)\d{4}$

I'm so whizzy at regular expressions!

Well, actually, I'm not very good at regular expressions. When I need to have one that's more complicated than dates or perhaps email addresses, I go shopping online by searching for "regular expression" with whatever it is I'm trying to match against. In Example 7-4, the format validated against was my own (well, I devised; others have probably used the same pattern), and was a simple regular expression that ensures only that the appropriate number of digits are given, that the characters are only digits, and that each grouping is of the right sizeall separated by dashes. Which, if you think about it, covers quite a bit.

Compare that, though, with the regular expression I just provided, created by Michael Ash and courtesy of the Regular Expression Library (an invaluable resource at http://regexlib.com/). This not only validates against the format, it also validates against what is known about Social Security numbersthe number groupings and so on. There are others at least as complex that can differentiate between a Visa credit card and a MasterCard.

If you want to become expert at regular expressions, spend some time at the Regular Expression Library, or you can also buy a copy of Friedl's Mastering Regular Expressions. This is the definitive guide on regular expressions.


On the other hand, do you need to differentiate between Visa and MasterCard? The important point to remember about regular expressions is that you can get carried away trying to find the perfect validation pattern, spending more time than the validation is worth. You have to weigh your time against how important it is to validate the entry before submitting it to the server.

Speaking of which, that's just about enough time on events, forms, and JiT validation. Time to move on to Chapter 8: JavaScript's roots, cookies, and evil things that go bump in the browser.

Forms Generation

I hate creating web-page forms; it's the most tedious part of web development. Luckily, there's plenty of web form-generation tools that are hosted online or that you can install on your site. They will not only generate your forms, they'll also start your server-side development for you. Though this technically isn't a JavaScript utility, it is a time-saving device, so I'm including it.

The one I've used the most is phpFormGenerator (http://phpformgen.sourceforge.net/). If your ISP provides cPanel for you to manage your account, it should be available as one of the many Fantastico-managed software applications.

This, and most other form generators, provide a way to specify the number and type of fields, give a name, and even associate a database field. Once the form is generated, you can add a script block to validate the entries once the form is submitted.

There's also an Eclipse plug-in that generates a form from XML. This tool is part of the Emerging Technologies Toolkit, a toolkit from IBM worth exploration even without the forms generator. Among the tools is the XForm Designer for forms generation and an Ajax Framework. Access the Toolkit at http://www.alphaworks.ibm.com/ettk.





Learning JavaScript
Learning JavaScript, 2nd Edition
ISBN: 0596521871
EAN: 2147483647
Year: 2006
Pages: 151

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net