Page 1 of 1

Validating Date

Posted: Tue Jul 26, 2005 6:06 am
by wyred
Hello all,
Just need a little help on reg expressions, I'm still new to this and I'm totally confused.

I want to validate a date, it has to be in the format MM/DD/YYYY.

This is what I have initially, seems to work fine.

Code: Select all

preg_match("#\d{2}/\d{2}/\d{4}#", '06/25/2005')
But when I tried to limit the month range to 1-12, it failed

Code: Select all

preg_match("#\d[1-12]{2}/\d{2}/\d{4}#", '06/25/2005')
What's the correct way to limit the month values to 01-12?

Posted: Tue Jul 26, 2005 6:14 am
by timvw
If i'm not mistaken you are allowing 2 numbers in (range of 1-1 and 2)


So i did a little websearch (i'm too lazy to think about your problems right now :P)... I typed in "regular expressions mm-dd-yyy" and i got this as the first page:

http://www.regular-expressions.info/reg ... dyyyy.html

Code: Select all

0ї1-9]|1ї012])ї- /.](0ї1-9]|ї12]ї0-9]|3ї01])ї- /.](19|20)\d\d

Posted: Tue Jul 26, 2005 6:23 am
by wyred
Ah, many thanks! :D

Looks confusing but I'll try understanding it again tomorrow with a cup of coffee. ( >_<)

Posted: Tue Jul 26, 2005 7:04 am
by tores
You could also use check_date...

Code: Select all

$date = '06/25/2005';
list($month, $day, $year) = explode('/', $date);
if (checkdate($month, $day, $year)) {
	echo "$date is a valid date";
} else {
	echo "$date is not a valid date";
}