Regex and ISO8601 formatted DateTime

TwystO picture TwystO · Oct 6, 2012 · Viewed 78.7k times · Source

I have a DateTime string ISO8601 formated

2012-10-06T04:13:00+00:00

and the following Regex which does not match this string

#(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})\+(\d{2})\:(\d{2})#

I can't figure out why it does not match.

I escaped metacharacters, for me it seems to be OK.

http://jsfiddle.net/5n5vk/2/

EDIT :

The right way: http://jsfiddle.net/5n5vk/3/

Answer

Édouard Lopez picture Édouard Lopez · Jan 14, 2013

Incomplete Regex

It's incomplete as it matches invalid date such as 2013-99-99T04:13:00+00:00.

Better solution

The regex below won't match this kind of invalid date (cf. ISO 8601 Date Validation That Doesn’t Suck). You can test with the following code :

re = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/
var testDates = {
    'date' : "2012-10-06T04:13:00+00:00",
    'validDate' : "0785-10-10T04:13:00+00:00",
    'invalidDate' : "2013-99-99T04:13:00+00:00",
    '1234Date': '1234'
}
for (var d in testDates) {
    if (re.test(testDates[d])) { console.info('[valid]: '+testDates[d]); }
    else { console.error('[invalid]: '+testDates[d]); }
}