du5591 2014-05-06 20:30
浏览 65

来自“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

  • 写回答

1条回答 默认 最新

  • doupinyan0186 2014-05-06 20:34
    关注

    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);
    
    评论

报告相同问题?

悬赏问题

  • ¥150 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装