【问题标题】:Symfony Validator doesnt check DateTime correctlySymfony Validator 没有正确检查 DateTime
【发布时间】:2017-02-27 15:26:26
【问题描述】:

我正在使用 Validator 来检查我的 var。其中一个是对象SeminarDate,其中包括startDateendDate。我的想法是用 Symfony Validator 检查日期。但是,它不起作用。例如:“+0200StackOverflow”是有效日期...

控制器中的部分操作

foreach($dataReq['date'] as $key_a => $a) {
            $SeminarDate = new SeminarDate;
            $SeminarDate->setStartDate(new \DateTime($a['startdate']));
            $SeminarDate->setEndDate(new \DateTime($a['enddate']));
            $SeminarDates[] = $SeminarDate;

            $errors = $validator->validate($SeminarDate);
            if(count($errors)>0){
                $errorString = (string) $errors;
                return new View($errorString);
            }
        } 

验证 yml 的一部分:

seminarDate:
            - Collection:
                fields:
                    startDate:
                        - Required:
                            - NotBlank:
                                message: 'startdate is required.'
                            - DateTime: ~

                    endDate:
                        - Required:
                            - DateTime: ~
                            - NotBlank:
                                message: 'endDate ist required.'

示例(向控制器发送 JSON 文件):

"date" : [
    { "startdate": "+0200Stackoverflow",
      "enddate" : "+0200Stackoverlfow"
    }
],

如果您需要更多,请询问。 谢谢

【问题讨论】:

  • 解释输入参数的是DateTime类。这适用于:new DateTime('now');php.net/manual/de/datetime.construct.php
  • 清除....谢谢....
  • print date('Y-m-d H:is',strtotime('+0200Stackoverflow'));#result 1970-01-01 01:0000 就是这里发生的事情。你从 DateTime 得到有效的日期,但它一定是无效的。

标签: php json validation datetime symfony


【解决方案1】:

您应该安装 php intl 扩展,以便正确的日期验证工作。

查看https://symfony.com/doc/current/setup.html#checking-symfony-application-configuration-and-setup

你可以去这里 http://localhost:8000/config.php 看看你有没有,或者在你的phpinfo中。

【讨论】:

    【解决方案2】:

    我这样做了,我只是创建了一个新的验证器并在将字符串添加到我的 Doctrine 类之前检查字符串本身。

    foreach($getData['date'] as $key => $value) {
                $validator = Validation::createValidator();
                if(!isset($value['startdate'])){
                    return new View('startdate doesnt exist.');
                } elseif(!isset($value['enddate'])){
                    return new View('enddate doesnt exist.');
                }
                foreach($value as $value1){
                    $violations = $validator->validate($value1, array(
                        new NotBlank(),
                        new DateTime(),
                    ));
                    if (count($violations)>0) {
                        return new View('date isnt valid!');
                    }
                }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-06
      • 2020-08-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多