这是我的代码
$arParams = $request->all();
$validator = Validation::createValidator();
$groups = new GroupSequence(['Default', 'custom']);
$constraint = new Assert\Collection([
'name' => new Assert\Length(['min' => 2]),
'city' => new Assert\Length(['min' => 2]),
'email' => new Assert\Email(),
'phone' => new Assert\Length(['min' => 18]),
'message' => new Assert\NotNull()
]);
$violations = $validator->validate($arParams, $constraint, $groups);
如果我遇到一些错误,我怎样才能获得像这样的数组 ['name' => 符号不足,'email' => 错误的电子邮件]?
我尝试在 $violations 上使用 foreach 但找不到其元素的所有方法 Phpstorm 将 $violation 标记为混合。我只发现 $violation->getMessage() 和 ->getCode()
最佳答案
推荐您阅读这篇文章https://symfony.com/doc/current/validation.html
如果验证失败,则返回非空错误列表(类 ConstraintViolationList )。
因此您可以通过以下方式获取列表:
if ($violations->count() > 0) {
$formatedViolationList = [];
for ($i = 0; $i < $violations->count(); $i++) {
$violation = $violations->get($i);
$formatedViolationList[] = array($violation->getPropertyPath() => $violation->getMessage());
}
}
几个解释。我们使用违规 api count()
中的方法或获取多个违规,在 for 循环后,我们使用 get($i)
按索引获取每个违规。在我们使用 getPropertyPath()
获取路径(属性名称)并使用 getMessage()
获取消息之后。
关于php - 如何从 $violations 获取数组 key => errorMessage。交响乐4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54217716/