2

I have encourred a strange problem when use a Symfony validator, the constraints violations is always empty even if entity does not respect constraints.

Entity :

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
  /**
  * @Assert\NotBlank()
  */
  public $name;
}

The code to use validator :

$Author = new Author();

$validator = Validation::createValidator();
var_dump( count($validator-> validate($Author)) );

Result : 0

Do you have an idea on the origin of this problem ?

Thanks in advance.

Jérémy

2 Answers 2

3

You do not use the validator pre-configured by Symfony. Is that intended? Usually you validate objects by either injecting the validator into your service or by pulling it from the container (its id is validator).

In your case, you are going to create a new validator instance. However, if not enabled explicitly, annotation support is turned off. You would have to enable it yourself (but the approach of using the configured validator service as written above is usually what you want to do):

$validator = Validation::createValidatorBuilder()
    ->enableAnnotationMapping()
    ->getValidator();
Sign up to request clarification or add additional context in comments.

1 Comment

As of Symfony 6, we also to have to call ->addDefaultDoctrineAnnotationReader() explicitly. Before, it was done by the enableAnnotationMapping() function.
0

enabled in the main config file:

# config/packages/framework.yaml
framework:
    validation: { enabled: true }

enable_annotations:

# config/packages/framework.yaml
framework:
    validation: { enable_annotations: true }

official doc: Validation Configuration

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.