3

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.

1 Answer 1

4

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(),
    ]));
    // ...............
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.