I currently have a problem with Symfony validators Optional constraints.
I need the parentId rules to only be processed if that field has been passed (the key is in the ParameterBag), unfortunately Symfony always tries to validate even when it is not passed.
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()],
]));
// ...............
}
Any help or pointers would be greatly appreciated as the Symfony docs mainly talk about validating against an object directly, but I want to validate against the ParameterBag coming in.
This should work
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(),
]));
// ...............
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments