Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate POST request in symfony 5

Tags:

php

symfony

Currently I'm using this method to validate data coming from a POST request:

//src/Controller/UserCreationController.php
//Creates collection
$constraints = new Collection([
    'username' => (new Required(new NotBlank())),
    'password' => (new Required(new NotBlank())),
    'email' => (new Required([new NotBlank(), new Email()])),
    'readAndAgree' => (new Required(new NotBlank())),
    'receiveUpdates' => (new Required(new NotBlank())),
]);

//Creates validator
$validator = Validation::createValidator();
$validation = $validator->validate(json_decode($request->getContent(), true), $constraints);

//Check for errors
if(count($validation) > 0) {
    //Return bad fields
    $errorsString = (string) $validation;
    return $this->json($errorsString, 400);
}

Is it possible to use Symfony's validator and create a custom validator for POST data? (most times not related to a model, so I couldn't find a good example). The goal is to make the controller's code cleaner, so I'm looking for possibilities in creating a new .yml in /config/validator, but all examples I can find are related to models and not custom data.

like image 634
Pedro Alca Avatar asked Sep 06 '25 23:09

Pedro Alca


1 Answers

If you do not want to use DTO you can use form component without connecting it with entity -> https://symfony.com/doc/current/form/without_class.html It's very clean and reusable solution. However there is also a way to do it in your way

class someClass {

private $validator;

public function __construct(ValidatorInterface $validator) {
    $this->validator = $validator;
}

public function yourMethod(array $postData) {
    // you can also create validator like that
    // $validator = Validation::createValidator();
    $constraints = new Assert\Collection([
        'username' => [
            new Assert\NotBlank()
        ],
        'email' => [
            new Assert\NotBlank(),
            new Assert\Email()
        ],
        ...
    ]);

    $validationResult = $this->validator->validate($postData, $constraints);
}
}

Read more about it in validating raw values section.

like image 61
sabat Avatar answered Sep 09 '25 19:09

sabat