tags:

views:

140

answers:

4

I have this regex (\d{4})-(\d{2})-(\d{2}) to detect a valid date, however, it is not perfect as some of the incoming data are 2009-24-09 (YYYY-DD-MM) and some are 2009-09-24 (YYYY-MM-DD).

Is it possible to have a one-line regex to detect whether the second & third portion is greater than 12 to better validate the date?

+2  A: 

Regex are not really good with dates validation, in my opinion is better to try to parse the date, and you could keep the regex as a sanity check before parsing it.

But if you still need it you can fix the month section using the following regex (\d{4})-(\d{2})-((1[012])|(0\d)|\d) but it goes downhill after that, since you need to check for correct days on months and leap years.

AlbertEin
@AlberEin - Agreed, I have another check later on, I just need a weak (but slightly better) check at this point.
John
Of what value is a "weak check" if you do another check later?
gary
A: 

to validate YYYY-MM-DD or YYYY-DD-MM:

$ptn = '/(\d{4})-(?:(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-2])|(0[1-9]|' .
  '[1-2][0-9]|3[0-2])-(0[1-9]|1[0-2]))/';
echo preg_match_all($ptn, '2009-24-09  2009-09-24 dd', $m);  // returns 2

even so, the date could be invalid, e.g.: 2010-02-29, to deal with that there's checkdate():

checkdate(2, 29, 2010);  // returns false
jspcal
+6  A: 

If you don't know the format, you will get ambiguous results.

take 2010-01-04 is that January 4th or March 1st?

You can't validate that with a regex.

As Albert said, try to parse the date, and make sure users know which format to use. You might try to separate the month and year portions into different fields or comboboxes.

Byron Whitlock
@Byron - There is no interaction between user and the script, the script is to parse bunch xml files etc.
John
A: 
(\d{4})-((0[1-9]|1[0-2])-(\d{2}))|((\d{2})-(0[1-9]|1[0-2]))

YYYY-(MM-DD)|(DD-MM)

hsz
You've got your precedence rules wrong; that regex matches `YYYY-MM-DD` **or** `DD-MM`. But fix that, and you're still left with the unresolvable ambiguity of dates like `2009-01-02`.
Alan Moore