...

View Full Version : Easy "regular expression" question/solution...



ShootingBlanks
11-16-2007, 04:24 PM
I'm sorry to bother people here with this, but I'm SOOOO bad with Regular Expressions. I just need a simple one to check if the data entered into a text field is in the date format YYYY-MM-DD. So, I'd need to check:

####-##-##

If anyone could help me finish the code below, I'd really appreciate it!:

if ($_POST) {
// ERROR CHECKING
if ($_POST['due_date'] DOES NOT MATCH THE YYYY-MM-DD FORMAT) {
$error = 'Please make sure that your date is in the format YYYY-MM-DD';
}
}

johnnyb
11-16-2007, 04:52 PM
This should work. It goes a little further checking that the YYYY is between 1000 and 2999, (restricts the first character to a 1 or 2), also, for the day it restricts the first character to a 0, 1, 2, or 3.

To only make sure that it's ####-##-## you could change the $date_pattern variable to:

$date_patterh = '/[0-9]{4}-[0-9]{2}-[0-9]{2}/'


if ($_POST) {
// ERROR CHECKING
$date_pattern = '/[12][0-9]{3}-[01][09]-[0-3][0-9]/'
if (!preg_match($date_pattern,$_POST['due_date'])) {
$error = 'Please make sure that your date is in the format YYYY-MM-DD';
}
}



I learned regular expressions from the tutorial at http://www.regular-expressions.info - they're not as scary as you think before you start learning them!

ShootingBlanks
11-16-2007, 05:05 PM
Works great - thanks!!!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum