Steve
Steve

Reputation: 101

Regex: expression matching a valid date but with minimum and maximum dates

I found this to validate a date in dd/MM/YYYY:

^(((((0[1-9])|(1\d)|(2[0-8]))\/((0[1-9])|(1[0-2])))|((31\/((0[13578])|(1[02])))|((29|30)\/((0[1,3-9])|(1[0-2])))))\/((20[0-9][0-9])|(19[0-9][0-9])))|((29\/02\/(19|20)(([02468][048])|([13579][26]))))$

How do I set minimum/maximum dates ?

Upvotes: 0

Views: 2985

Answers (3)

kev
kev

Reputation: 161864

Programming languages(such asjava, C#, python, etc) have date/time/datetime type.
date can be created via constructor if you supply valid arguments.
If not, it will product exception which can be captured(usually try...catch statement).
It's hard to validate 29/2/2012 and 29/2/2013 using regex.
But it's easy with the help of date type of the language.

$ python
>>> import time
>>> time.strptime('29/2/2012', '%d/%m/%Y')
time.struct_time(tm_year=2012, tm_mon=2, tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=60, tm_isdst=-1)
>>> time.strptime('29/2/2013', '%d/%m/%Y')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.2/_strptime.py", line 482, in _strptime_time
    tt = _strptime(data_string, format)[0]
  File "/usr/lib/python3.2/_strptime.py", line 459, in _strptime
    datetime_date(year, 1, 1).toordinal() + 1
ValueError: day is out of range for month

Upvotes: 1

Zsolt Botykai
Zsolt Botykai

Reputation: 51653

For comparing dates you can use date.js too.

HTH

Upvotes: 0

Brigand
Brigand

Reputation: 86260

If you use that plugin, at least you know you'll have a valid date from a formatting standpoint. Then it's the job of JavaScript to parse the date and determine all of the rules.

This function isn't complete, so if anyone adds on to it: press the update button and drop the link here. If it's more complete I'll update this post.

I couldn't imagine doing real validation of a date in RegEx.

Upvotes: 0

Related Questions