3

I created a contoller in Symfony that will be handle API requests. I want to validate action request. Parameter 'type' of the request must be integer. There is controller action code:

public function store(ValidatorInterface $validator, Request $request): JsonResponse
{
    $collection = new Collection([
        'type' => [
            new Assert\Type('int'),
            new Assert\Range(['min' => 1, 'max' => 2])
        ]
    ]);

    $errors = $validator->validate($request->request->all(), $collection);
    if ($errors->count()) {
        dd($errors);
    }

    return new JsonResponse('OK');
}

But when I tested this action via Postman, validation is failed with error "This value should be of type int." event if I send response with int value:

my response

What is the right way to validate int param or string param as int in Symfony?

1
  • I'm pretty sure your problem is that form-data sends everything as strings (I might be wrong). But one way to overcome this would be to send json. Commented Oct 4, 2022 at 1:15

1 Answer 1

4

You can use the digit type for the type validator. Then the validator will check the type via the ctype_digit function

new Assert\Type('digit'),
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.