Main Page

Common Patterns

Common Patterns
On the Web, regular expressions are most often used to validate user input before sending data back to
the server. This is, after all, why JavaScript was initially created.
The patterns most commonly tested for on the Web are the following:
Credit Cards
E-mail Addresses
Each of these data types represents a different problem to solve. Some involve numbers only, others
involve non-alphanumeric characters, and still others include characters that can be ignored. By study-
ing these four patterns, you can sharpen your regular expression skills.
Validating dates
For many Web developers, dates are a major headache. Despite the advent of nifty layer-based, pop-up
calendar systems, users really just want to be able to type in a date. Most developers cringe at the idea
of letting a user manually enter a date. Many different date patterns are used around the world, not to
mention the internationalized month and day names! Many sites use three form fields for date entry,
usually comprised of two combo boxes (one with month names, the other with day numbers) and a text
field for the year (although sometimes this, too, is a combo box). Although this approach is okay, it still
leaves users wanting to type in a date, which is much faster than tabbing through three fields and click-
ing up or down to select an item in a combo box.
Think back to Chapter 3, “Object Basics,” and the discussion about
, which can parse sev-
eral string patterns into millisecond representations of dates. As a quick review, these are the supported
m/d/yyyy (such as 6/13/2004)
mmmm d, yyyy (such as January 12, 2004)
But what if you want to allow users to enter a date in the form dd/mm/yyyy (such as 25/06/2004),
which is popular in Europe? This is where regular expressions can help.
To start discerning a pattern, consider the various ways a date in the format can be represented. For
instance, a month is always two digits, numbers 01 through 12; the day also must always have two digits
that must be numbers 01 through 31. So, the month and day must be two-digit numbers whereas the
year must have four digits. Start with a simple pattern, like this:
var reDate = /\d{1,2}\/\d{1,2}\/\d{4}/;
This pattern matches the basic format of dd/mm/yyyy, but it doesn’t take into account the range of
valid numbers for days or months. The result of this could be a false positive when matched against a
date such as 55/44/2004. To solve this problem, consider a pattern for recording just the day: The first
Chapter 7
10_579088 ch07.qxd 3/28/05 11:38 AM Page 216

JavaScript EditorFree JavaScript Editor     Ajax Editor