Hallo,

Please check this pattern to validate an date with regex. it doesn't work for the last two numbers.

$var = "2005-14-30";
if (ereg("^[12][0-9]{3}[-:,./[:space:]]((0[1-9])|(1[0-2]))[-:,./[:space:]]((0[1-9])|([12][0-9])|(3[01]))$", $var)) {
	echo "OK";
}
    <?
    //validate the days in the month making the leading 0
    //optional
    $d = "([0-2]*[1-9]|3[0-1])";
    
    //validate the month it can be zero padded, but doesn't 
    //have to be. 
    $m = "(([0]*[1-9])|(1[0-2]))";
    
    //validate the year. It can be a four digit year that sarts 
    //with 19 or 20 followed by two digits or it can be a two 
    //digit year which is simply two digits. Though I personall
    //recommend forcing a four digit year by using the 
    //following coomented code instead
    //$y = "(19|20)[0-9]{2}";
    $y = "(((19|20)[0-9]{2})|([0-9]{2}))";
    
    //this defines all the legal seperators
    $s = "[-:,./[:space:]]";
    
    //now we just string those all together into the ereg
    ereg("^" . $d . $s . $m . $s . $y . "$",$var);
    ?>

    Splitting complex regexes up like this makes it easier to validate them and spot errors. Because you can test each portion individually. So you can make sure the days regex works without worring about the other portions of the regex. Though I don't recommend using this alone as it does not validate that their days is valid for the specific month you'll need an if statment for that.

      Hallo drawmack,

      thanks for hint with the leading zeros, the optimized year-version looks better too.

      Your are right there is no validation that check the right days for a month. It's just a controll for a not existing date.

      Funny is that my pattern is OK, the var holds a month with the value of 14

      :eek:

        Write a Reply...