phpsymfonyvalidationsymfony-validator

Handle Entity classes with Symfony Validator component


I'm trying to use symfony/validator outside of Symfony by just installing composer require symfony/validator (vemphasized text7.1)

Following this guide https://symfony.com/doc/current/components/validator.html

I now have:

$validator = Validation::createValidator();
$violations = $validator->validate($someName, [
    new Length(['min' => 10]),
    new NotBlank(),
]);

This validation works fine.

But I would like validation like in this guide: https://symfony.com/doc/current/validation.html So that I can validate something like this:

// src/Entity/Author.php
<?php

namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\NotBlank]
    public string $name;
}

When I now try to validate it $violations is always 0 even if the name is null

    $author = new Author();
    $author->name = null;
    $validator = Validation::createValidator();
    $violations = $validator->validate($author);

The documentation isn't very clear on this but it looks like the standalone version is incapable of handling a class like this.

Is something like this possible with the standalone version?


Solution

  • After battling this one for hours, and trying various solutions provided online as well as @Arno van Oordt's answer which did not work for me, I figured it out and it was so simple.

    <?php
    
    namespace App\Domain\Entities;
    
    use Symfony\Component\Validator\Constraints as Assert;
    
    class Slug
    {
        #[Assert\NotBlank]
        #[Assert\Type('string')]
        private string $slug;
        
        public function setSlug(): string
        {
            return $this->slug;
        }
    
    }
    
    

    This is what worked for me

    <?php
    
    use Symfony\Component\Validator\Validation;
    
    $validator = Validation::createValidatorBuilder()
        ->enableAttributeMapping()
        ->getValidator();
    
    
    
    $slug = new Slug();
    $slug->setSlug('the_slug_string')
    
    $validator->validate($slug);
    
    

    The key that I was missing was ->enableAttributeMapping() that I had been missing.

    So in your case it will look like this

    $author = new Author();
    $author->name = null;
    $validator = Validation::createValidatorBuilder()
        ->enableAttributeMapping()
        ->getValidator();
    
    $violations = $validator->validate($author);