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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With