使用上一个集合项的最后一个约束的silex验证器

时间:2016-01-28 10:02:19

标签: validation symfony silex

基于tutorial在silex中进行验证,我创建了一个约束:

    $constraint = new Assert\Collection([
        'token' => [
            new Assert\NotBlank(),
            new Assert\Length(['min' => Constant::TOKEN_LENGTH, 'max' => Constant::TOKEN_LENGTH]),
        ],
        'languageCode' => [
            new Assert\NotBlank(),
            new Assert\Choice(['choices' => [Constant::LANGUAGE_CODE_DE, Constant::LANGUAGE_CODE_EN]])
        ],
        'startDate' => [
            new Assert\NotBlank(),
            new Assert\Date()
        ],
        'endDate' => [
            new Assert\NotBlank(),
            new Assert\Date()
        ],
        'duration' => [
            new Assert\GreaterThanOrEqual(['value' => 1])
        ],
    ]);

应与以下结构匹配(此处来自json):

{
    "token": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "languageCode": "DE",
    "startDate": "2016-01-01",
    "endDate": "2016-01-05",
    "duration": 1
}

{
    "token": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
    "languageCode": "DE",
    "startDate": "2016-01-01",
    "endDate": "2016-01-05"
}

虽然第一个示例按预期验证,但第二个示例(具有可选的持续时间)将以奇怪的行为响应:来自" endDate"的约束。使用地点:

object(Symfony\Component\Validator\ConstraintViolationList)[154]
  private 'violations' => 
    array (size=1)
      0 => 
        object(Symfony\Component\Validator\ConstraintViolation)[158]
          private 'message' => string 'This field is missing.' (length=22)
          private 'messageTemplate' => string 'This field is missing.' (length=22)
          private 'parameters' => 
            array (size=1)
              '{{ field }}' => string '"duration"' (length=10)
          private 'plural' => null
          private 'root' => 
            array (size=4)
              'token' => string 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' (length=64)
              'languageCode' => string 'DE' (length=2)
              'startDate' => string '2016-01-01' (length=10)
              'endDate' => string '2016-01-05' (length=10)
          private 'propertyPath' => string '[duration]' (length=10)
          private 'invalidValue' => null
          private 'constraint' => 
            object(Symfony\Component\Validator\Constraints\Date)[136]
              public 'message' => string 'This value is not a valid date.' (length=31)
              public 'payload' => null
              public 'groups' => 
                array (size=1)
                  0 => string 'Default' (length=7)
          private 'code' => string '2fa2158c-2a7f-484b-98aa-975522539ff8' (length=36)
          private 'cause' => null

我没有看到任何理由......

1 个答案:

答案 0 :(得分:0)

尝试添加参数allowMissingFields

$constraint = new Assert\Collection([
    'allowMissingFields' => true,
    'fields' => [asserts...]
]);