我想知道如何在 symfony 中验证数组数组。
我的验证规则是:
到目前为止,我已经这样做了:
$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内部约束 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()
}
)
}
)
关于symfony - 如何在 Symfony 4 中验证数组数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374344/