Page 1 of 1
regexp newbie question
Posted: Fri Feb 22, 2008 8:27 am
by PhpDog
I'm new to using regular expressions and need to validate a date format for the correct (for me) format of dd/mm/yyyy.
$formatFlag = 0;
// --- correct format? ------
if(!(ereg("^([0-9]{2})/([0-9]{2})/([0-9]{4})",$dateString)))
{
$formatFlag = 1;
}
so $formatFlag is 0 for valid date format, but 1 if invalid date format.
Does the regexp look right to you guys?
Re: regexp newbie question
Posted: Fri Feb 22, 2008 8:36 am
by Scrumpy.Gums
It will match the correct format, yes. However, it will also match invalid dates e.g. 99/99/9999, since you're only checking if there are the correct amount of numbers.
You're missing a $ on the end, so it would also match "99/99/9999asalkdfjhasfoiu183u" since your regexp is basically saying `match any string that starts with xx/xx/xxxx where x are 0-9'
A good resource for regexp is
http://www.regular-expressions.info/dates.html.
Hope that helps.

Re: regexp newbie question
Posted: Fri Feb 22, 2008 8:55 am
by PhpDog
Many thanks for the link.
The string length is OK as the html form textfield will only allow a max of 10 characters.
However, if I use:
Code: Select all
// ------------- validate any dates entered ----------------------------------------------------------
function validDate($dateString)
{
$dateString = trim($dateString);
$formatFlag = 0;
// --- correct length? -------
if(strlen($dateString != 10))
{
$formatFlag = 1;
}
// --- correct format? ------
if(!(ereg("^([0-9]{2})/([0-9]{2})/([0-9]{4})",$dateString)))
{
$formatFlag = 1;
}
// --- valid date? ------
if($formatFlag == 0)
{
$dd = intval(substr($dateString,0,2));
$mm = intval(substr($dateString,3,2));
$yy = intval(substr($dateString,6,4));
$dateChecked = checkdate($mm, $dd, $yy);
if($dateChecked == 0)
{
$formatFlag = 2;
}
}
return $formatFlag;
}
echo $dateFrom." flag = ".validDate($dateFrom);
and fire 32/02/2002 at it I would expect validDate($dateFrom) to return '32/02/2002 flag = 2'. Whereas now I get '32/02/2002 flag = 1'.
Any please see why this is? As the string length and format is OK, albeit an invalid date.
Re: regexp newbie question
Posted: Fri Feb 22, 2008 9:06 am
by Scrumpy.Gums
Take a look at line 9.

...should be
instead of
Re: regexp newbie question
Posted: Fri Feb 22, 2008 9:11 am
by PhpDog
Please accept my grateful thanks for spotting that.
Some days you look at your own code and ...

Re: regexp newbie question
Posted: Fri Feb 22, 2008 11:45 am
by RobertGonzalez
Moved to the RegExp forum.