来自“Murach的PHP”的正则表达式生日日期验证

I want to make sure that the birthday entered is not in the future. If I input a future date it should show an error message.

public function birth($name, $value) {
    $datePattern = '/^[0-9]{2}\/[1-9]{2}\/[1-9]{4}?$/';
    $match = preg_match($datePattern, $value);
    if ( $match === false ) {
        $field->setErrorMessage('Error testing field.');
       return;
    }
    if ( $match != 1 ) {
        $field->setErrorMessage('Invalid date format.');
        return;        
    }
    $dateParts = explode('/', $value);// i try to see if i could take everything after / to form an array 
    $month = $dateParts[0];
    $day  = $dateParts[1];
    $year  = $dateParts[2];
    $dateString = $month . $day . $year;
    $exp = new \DateTime($dateString);
    $now = new \DateTime();
    if ( $exp < $now ) {
        $field->setErrorMessage('Cant be a date after the current date');
        return;
    }

    $field->clearErrorMessage();
}

However it's not working correctly. I can't compare $dateString with DateTime

You don't need a regex for that - just compare it to the current date.

public function birth($name, $value) {
    $timestamp = strtotime($value);
    if ($timestamp === FALSE) {
        // $value is not a valid date
    }
    if ($timestamp > time()) {
        // date is in the future
    }
}

However if you want to keep your current code, the problem is in this line

$dateString = $month . $day . $year;

This is not a valid date representation. Today would be 572014 - you need to add / in between and it will work.

$dateString = sprintf("%u/%u/%u", $month, $day, $year);