Symfony validation: declaring rules with constraints

Validation in Symfony declares on the entity, with constraints, what a piece of data must respect: presence, format, bounds, uniqueness.

#[ORM\Entity(repositoryClass: InscriptionRepository::class)]
#[UniqueEntity(fields: ['soiree', 'email'], message: 'You are already registered for this evening.', errorPath: 'email')]
class Inscription
{
    #[ORM\Column(length: 180)]
    #[Assert\NotBlank(message: 'Enter your e-mail address.')]
    #[Assert\Email(message: 'Enter a valid e-mail address.')]
    private ?string $email = null;

    #[ORM\Column]
    #[Assert\Range(notInRangeMessage: 'From {{ min }} to {{ max }} people per registration.', min: 1, max: 6)]
    private int $personnes = 1;
}

Rules are written once, where the data lives: #[Assert\NotBlank], #[Assert\Length], #[Assert\Range] or #[Assert\GreaterThan('now')] on the properties, #[UniqueEntity] on the class, each with its message. A form, #[MapRequestPayload] or a command then apply them without repeating them. For a simple URL parameter, #[MapQueryParameter] already validates the type and the bounds through its filter options. The trap: #[UniqueEntity] on two fields attaches the error to the first one, soiree, which the form doesn't display. Without errorPath: 'email', the message lands at the top of the form, far from the field to fix.

The exercises have you reject a number of guests outside 1 to 12 in the URL, then put the constraints and their messages on the storytelling evenings and their registrations, including one registration per address and per evening. On the Laravel side, an exercise replaces a closure with the array_keys rule, which only accepts the expected keys in an array.

7 exercises work on this concept, by writing code in the browser.

In the tracks

In Practice

Related concepts

422Forms$_POSThtmlspecialchars()Query string#[MapQueryParameter]MigrationsError handling