Symfony News

New in Symfony 4.3: Automatic validation

Kévin Dunglas

Contributed by
Kévin Dunglas
in #27735.

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 when persisting the entity?

1
2
$entity = new SomeEntity();
$entity->pinCode = '1234567890';

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
$validationResult = $this->validator->validate($entity);

var_dump((string) $validationResult);
// Object(App\Entity\SomeEntity).columnLength:\n
//     This value is too long. It should have 20 characters or less.
//     (code d94b19cc-114f-4f44-9cc4-4138e80a87b9)\n

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=true and type=... requires to have the PropertyInfo component installed.

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.


Be trained by Symfony experts - 2019-04-4 Clichy - 2019-04-10 Clichy - 2019-04-15 Clichy


About us

What a Symfony developer should know about the framework: News, Jobs, Tweets, Events, Videos,...

Resources

Find us on Twitter

Find us on Facebook