Validating Date

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
wyred
Forum Commoner
Posts: 86
Joined: Mon Dec 20, 2004 1:59 am
Location: Singapore

Validating Date

Post 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?
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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
wyred
Forum Commoner
Posts: 86
Joined: Mon Dec 20, 2004 1:59 am
Location: Singapore

Post by wyred »

Ah, many thanks! :D

Looks confusing but I'll try understanding it again tomorrow with a cup of coffee. ( >_<)
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Post 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";
}
Post Reply