我目前在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。
答案 0 :(得分:1)
这应该有效
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(),
]));
// ...............
}