Symfony 可选约束未按预期工作
Symfony Optional constraints not working as expected
我目前遇到 Symfony 验证器可选约束的问题。
我只需要在该字段已通过时才处理 parentId 规则(密钥在 ParameterBag 中),不幸的是 Symfony 总是尝试验证即使它没有通过。
public function validateParameters(ParameterBag $request, Collection $validatorRules)
{
$validatorErrors = $this->validator->validateValue($request->all(), $validatorRules);
if (count($validatorErrors) !== 0) {
throw new \Exception($validatorErrors[0]->getPropertyPath() . ' - ' . $validatorErrors[0]->getMessage());
}
echo 'yay!';
exit;
}
public function create(Application $app, Request $request)
{
// check that the validation rules pass for this service
$this->validateParameters($request->request, new Collection([
'parentId' => [new Assert\Optional(), new Assert\Regex(['pattern' => '/^[0-9]\d*$/'])],
'title' => [new Assert\NotBlank(), new Assert\Length(['min' => 3])],
'description' => [new Assert\NotBlank()],
]));
// ...............
}
任何帮助或指示将不胜感激,因为 Symfony 文档主要讨论直接针对对象进行验证,但我想针对传入的 ParameterBag 进行验证。
这应该有效
public function create(Application $app, Request $request)
{
// check that the validation rules pass for this service
$this->validateParameters($request->request, new Collection([
'parentId' => new Assert\Optional([
new Assert\Regex(['pattern' => '/^[0-9]\d*$/'])
]),
'title' => [
new Assert\NotBlank(),
new Assert\Length(['min' => 3])
],
'description' => new Assert\NotBlank(),
]));
// ...............
}
我目前遇到 Symfony 验证器可选约束的问题。
我只需要在该字段已通过时才处理 parentId 规则(密钥在 ParameterBag 中),不幸的是 Symfony 总是尝试验证即使它没有通过。
public function validateParameters(ParameterBag $request, Collection $validatorRules)
{
$validatorErrors = $this->validator->validateValue($request->all(), $validatorRules);
if (count($validatorErrors) !== 0) {
throw new \Exception($validatorErrors[0]->getPropertyPath() . ' - ' . $validatorErrors[0]->getMessage());
}
echo 'yay!';
exit;
}
public function create(Application $app, Request $request)
{
// check that the validation rules pass for this service
$this->validateParameters($request->request, new Collection([
'parentId' => [new Assert\Optional(), new Assert\Regex(['pattern' => '/^[0-9]\d*$/'])],
'title' => [new Assert\NotBlank(), new Assert\Length(['min' => 3])],
'description' => [new Assert\NotBlank()],
]));
// ...............
}
任何帮助或指示将不胜感激,因为 Symfony 文档主要讨论直接针对对象进行验证,但我想针对传入的 ParameterBag 进行验证。
这应该有效
public function create(Application $app, Request $request)
{
// check that the validation rules pass for this service
$this->validateParameters($request->request, new Collection([
'parentId' => new Assert\Optional([
new Assert\Regex(['pattern' => '/^[0-9]\d*$/'])
]),
'title' => [
new Assert\NotBlank(),
new Assert\Length(['min' => 3])
],
'description' => new Assert\NotBlank(),
]));
// ...............
}