0

I want to know the regex for date dd-mm-yyyy format. And the rule is

The ·day· value must be no more than 30 if ·month· is one of 4, 6, 9, or 11, no more than 28 if ·month· is 2 and ·year· is not divisible by 4, or is divisible by 100 but not by 400, and no more than 29 if ·month· is 2 and ·year· is divisible by 400, or by 4 but not by 100.

I wanted to do in xml regex in my xsd.

Accept-- 29-02-2000, 31-05-2013, 30-04-2012

Reject-- 29-02-1900, 31-04-2013, 30-02-2000

Sai
  • 81
  • 2
  • 8

2 Answers2

6

I actually had this regex lying around, I made it a while back as a competition with a friend of mine!

The following is my friend's, and about 20% faster:

^(?!00)((([0-2]\d|3[01])-(0[13578]|1[02])|([0-2]\d|30)-(0[469]|11)|([01]\d|2[0-8])-02)-\d{4}|([01]\d|2\d)-02-(([02468][048]|[13579][26])(?=00)|\d{2}(?!00))([02468][048]|[13579][26]))$

While this one is the shortest (fits on twitter, which was my challenge):

^(?!(00|30-02))(((?=.+(?!00)([02468](?=[048](00)?$)|[13579](?=[26](00)?$)))|(?!29-02))[012]\d|30|31(?!-(0[2469]|11)))-(0[1-9]|1[012])-\d{4}$

Note that both regexes will fail to validate for yyyy = 0000, it's not a valid year, according to the gregorian calendar.

Both regexes are free of lookbehinds and conditionals, as it had to work in javascript.

EDIT:

Since you need this for XML, I've modified the first regex a bit, it only needed slight modification to get rid of the lookaround.

((0[1-9]|[1-2]\d|3[01])-(0[13578]|1[02])|([0-2]\d|30)-(0[469]|11)|(0[1-9]|1\d|2[0-8])-02)-\d{4}|(0[1-9]|[12]\d)-02-(([02468][048]|[13579][26])00|(\d{2}([02468][48]|[2468][048]|[13579][26])))

I hope this works for you.

melwil
  • 2,547
  • 1
  • 19
  • 34
  • Thanks @melwil. But I need to do it in xml regex. – Sai May 22 '13 at 09:29
  • W3C XML flavors are too limited to make an exact validation for all dates. Matching for leap years without any for of lookaround is next to impossible, at least I do not want to think of the length. Validation should be done by the program that creates this XML, since XML simply was not made to validate data, only represent it. – melwil May 22 '13 at 09:44
  • I decided to try anyway. It turned out to be easier than I thought. I'll update the answer. – melwil May 22 '13 at 10:03
1

You should validate a date with the following code instead of a regex:

DateTime temp;
if(DateTime.TryParse(dateTextBox.Text, out temp))
// valid date
else
// invalid date
Alexandru Dicu
  • 1,151
  • 1
  • 16
  • 24