April 2, 2019 Javier Eguiluz

Consider the following simple Doctrine entity:

1 2 3 4 5 6 7 8 9 10 use Doctrine\ORM\Mapping as ORM ; /** @ORM\Entity */ class SomeEntity { // ... /** @ORM\Column(length=4) */ public $pinCode ; }

Will the following code result in a validation error?

1 2 3 $entity = new SomeEntity (); $entity -> pinCode = '1234567890' ; $violationList = $validator -> validate ( $entity );

The answer is ... no. Surprisingly, many Symfony developers still don't realize that the Doctrine mapping configuration (e.g. @ORM\Column(length=4) ) doesn't actually validate anything. This config is just a hint for the Doctrine schema generator. This can lead to usability and even security issues.

In Symfony 4.3 we improved this by introducing automatic validation based on Doctrine mapping. That's why in Symfony 4.3, the previous example would have produced the following result:

1 2 3 4 5 6 $violationList = $validator -> validate ( $entity ); var_dump (( string ) $violationList ); // Object(App\Entity\SomeEntity).columnLength:

// This value is too long. It should have 4 characters or less. // (code d94b19cc-114f-4f44-9cc4-4138e80a87b9)



This new feature introspects mappings like @ORM\Column(length=4) to add the related @Assert\Length(max=4) validation automatically to that same property. Specifically, the following validations are automated:

Doctrine mapping Automatic validation constraint nullable=false @Assert\NotNull type=... @Assert\Type(...) unique=true @UniqueEntity length=... @Assert\Length(...)

The automatic validation of nullable=false and type=... requires to have the PropertyInfo component installed. Also, this new feature will be disabled by default, but enabled for new projects.

Since the Form component as well as API Platform internally use the Validator component, all your forms and web APIs will also automatically benefit from these automatic constraints.

Lastly, keep in mind that, although this automatic validation is convenient, it's not enough for most applications, so you will still need to manually configure more Symfony validation constraints.