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; ...
Get Learning JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.