Manual validation of an object with the Symfony validator component

Published on 2023-08-09 • Modified on 2023-08-09

In a previous snippet, we saw how to validate an array using the existing validator service manually. In this snippet, we manually create a validator service, and then we validate an object containing validation assertions with attributes like #[Assert\NotBlank].



namespace App\Controller\Snippet;

use App\Samples\ProductSample;
use Symfony\Component\Validator\ConstraintViolation;
use Symfony\Component\Validator\Validation;

 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
trait Snippet267Trait
    public function snippet267(): void
        $validator = Validation::createValidatorBuilder()
        $product = new ProductSample();
        /** @var ConstraintViolation $violations */
        $violations = $validator->validate($product);
        echo 'Violations: '.PHP_EOL.$violations;

        // That's it! 😁

 Run this snippet  More on Stackoverflow  More on the web  Random snippet

  Work with me!