如何在 Symfony 4 中验证数组的数组

How to validate array of arrays in Symfony 4

我想知道如何在 symfony 中验证数组的数组。 我的验证规则是:

  1. 用户 - 非空白
  2. 日期 - 日期和非空白
  3. 存在 - 非空白

到目前为止我已经这样做了:

$validator = Validation::createValidator();

$constraint = new Assert\Collection(array(
        'user' => new Assert\NotBlank(),
        'date' => new Assert\Date(),
        'present' => new Assert\NotBlank()
));

$violations = $validator->validate($request->request->get('absences')[0], $constraint);

但问题是它只允许验证单个数组,例如
$request->request->get('absences')[0].

数组如下所示:

您必须设置 Collection constraint inside All 约束条件:

When applied to an array (or Traversable object), this constraint allows you to apply a collection of constraints to each element of the array.

因此,您的代码可能如下所示:

$constraint = new Assert\All(['constraints' => [
    new Assert\Collection([
        'user' => new Assert\NotBlank(),
        'date' => new Assert\Date(),
        'present' => new Assert\NotBlank()
    ])
]]);

更新:如果你想为此使用注释,它看起来像这样:

@Assert\All(
    constraints={
        @Assert\Collection(
            fields={
                "user"=@Assert\NotBlank(),
                "date"=@Assert\Date(),
                "present"=@Assert\NotBlank()
            }
        )
    }
)