Tuesday, December 4, 2007

More Regex

When the problem of validating a date came up, it was regular expressions to the rescue.
The following will validate a date in the form of mm/dd/yyyy and could be modified for other forms:
^((0[13578]|1[02])\/([012]\d|3[01])\/(19|20)\d{2}|
(0[468]|11)\/([012]\d|30)\/(19|20)\d{2}|
02\/([01]\d|2[1-8])\/(19|20)\d{2}|
02\/29\/(2[048]00|(19|20)(0[48]|[2468][048]|[13579][26])))$

(note: join on a single line)

If you end up using this, keep in mind that it has to be mm/dd/yyyy that means
01/06/0045 will work
2/7/1932 will not

what does this check
checks that a month 01-12 is entered
for months 1,3,5,7,8,10, and 12 it checks that the day is 01-31
for months 4,6,9, and 11 it checks that the day is 01-30
for month 2 it checks that the day is 01-28
for the above it checks that the year is 1900-2099
if the month is 2 and the day is 29 it checks that the year is
2000, 2400, 2800, or divisible by 4 but not 100