Main Page

Combining the patterns

digit can be any number 0–3 and the second digit (which is required) can be any number 0–9. Therefore,
a logical pattern for the day would be as follows:
var reDay = /[0-3]?[0-9]/;
However, this expression also matches 32 through 39, which are never valid days. By using alternation
and character classes, you can come up with an all-encompassing day pattern:
var reDay = /0[1-9]|[12][0-9]|3[01]/;
This regular expression correctly matches all day values where 0 can be before any number 1 through 9,
but not another 0, or the number can begin with 1 or 2 and can be followed by any number 0 through 9.
Finally, the number can begin with a 3 and be followed by only a 0 or a 1. Now, you move on to format-
ting the month.
The month pattern is very much like the day pattern except without as many options:
var reMonth = /0[1-9]|1[0-2]/;
The pattern presented here matches all numbers 01 through 12, without exception. The last step is to
create a pattern for the year.
Two modes of thinking exist about allowing users to enter the year. The first is to let them enter whatever
year they want (so long as it’s numerical) and let them deal with any problems associated with setting a
due date in the distant future. The second is to limit the valid years to those from 1900 through 2099, with
the logic being that by the time 2099 comes around, chances are any system using this code will have been
put out to pasture a long time ago.
For the purpose of building a complete example, consider the second mode of thought. This can be
accomplished with the following regular expression:
var reYear = /19|20\d{2}/;
All years between 1900 and 2099 will match this pattern, which starts by declaring a year must start with
either 19 or 20 followed by two more digits.
Combining the patterns for the day, month, and year into one, you get:
var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
Notice that the complete pattern puts each part of the date into a non-capturing group. This is necessary
to ensure that the alternations don’t run into one another. You can, of course, use capturing groups if you
have the need.
Finally, it’s much easier to use a function to check if a date is valid, so you can wrap the regular expres-
sion and the test in a function called
function isValidDate(sText) {
var reDate = /(?:0[1-9]|[12][0-9]|3[01])\/(?:0[1-9]|1[0-2])\/(?:19|20\d{2})/;
return reDate.test(sText);
Regular Expressions
10_579088 ch07.qxd 3/28/05 11:38 AM Page 217

JavaScript EditorFree JavaScript Editor     Ajax Editor