Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 62 ยท Forms and Validation

Validation

Learn the Symfony Validator component: constraint attributes, validation groups, nested objects, arrays and violations, with runnable validator stand-ins.

Every application has to answer the same question about incoming data: is this acceptable? A username that is empty, an e-mail without an @, an age of 400. In Symfony this question is handled by the Validator component, and it is deliberately separate from forms. The validator knows nothing about HTML or HTTP. You give it a value (an object or an array) and a set of rules, and it gives you back a list of violations.

That separation is the main idea of this lesson. You describe the rules once, next to the data (usually as PHP attributes on a class), and then the same rules protect a form, a JSON API, a console command or a message handler. In Handling Submission and CSRF you saw forms ask the validator for errors; here you meet the validator itself.

How validation flows

flowchart LR
    DATA["Object or array"] --> V["Validator"]
    META["Constraints<br/>(attributes on the class)"] --> V
    V --> LIST["ConstraintViolationList"]
    LIST -->|"empty"| OK["Valid: continue"]
    LIST -->|"not empty"| ERR["Show errors or return 422"]

The validator combines the data with its constraints and returns a list of violations; an empty list means valid.

Constraints as attributes

A constraint is a small object that says what must be true. You attach constraints to properties with attributes from the Symfony\Component\Validator\Constraints namespace, usually imported with the alias Assert:

PHP
<?php

namespace App\Dto;

use Symfony\Component\Validator\Constraints as Assert;

class Registration
{
    #[Assert\NotBlank]
    #[Assert\Length(min: 3, max: 20)]
    public ?string $username = null;

    #[Assert\NotBlank]
    #[Assert\Email]
    public ?string $email = null;

    #[Assert\Range(min: 18, max: 120)]
    public ?int $age = null;

    #[Assert\NotBlank(groups: ['registration'])]
    #[Assert\Length(min: 8, groups: ['registration'])]
    public ?string $plainPassword = null;
}

Some constraints you will use constantly: NotBlank, NotNull, Length, Email, Range, Positive, GreaterThan, Choice, Regex, Count (for collections), Type and Url. Every constraint has a message option, and messages can contain placeholders such as {{ value }} or {{ limit }}.

One rule surprises beginners: most constraints treat null and an empty string as valid. Length(min: 3) does not complain about an empty value, because the job of "something must be present" belongs to NotBlank or NotNull. That is why username above carries both. Combining a presence constraint with a format constraint gives you precise, non-repetitive messages.

Running the validator

In a Symfony application you inject ValidatorInterface. It returns a ConstraintViolationList, which you can count and loop over:

PHP
<?php

use Symfony\Component\Validator\Validator\ValidatorInterface;

public function register(ValidatorInterface $validator): Response
{
    $registration = new Registration();
    $registration->username = 'al';
    $registration->email = 'not-an-email';

    $violations = $validator->validate($registration);

    foreach ($violations as $violation) {
        // $violation->getPropertyPath() -> "username"
        // $violation->getMessage()      -> "This value is too short. ..."
        // $violation->getInvalidValue() -> "al"
    }

    return count($violations) === 0
        ? new Response('ok')
        : new Response((string) $violations, 422);
}

Each ConstraintViolation records the property path (username, or address.city for nested data), the translated message and the value that failed. The validator never throws for bad data; throwing is reserved for programmer mistakes such as an unknown constraint.

Symfony itself cannot run on this site, so the example above is read-only. The stand-in below rebuilds the idea in plain PHP: constraints are attributes, and a small validator reads them with reflection, exactly the way the real component discovers its metadata. The groups at the end are explained in the next section.

PHP A tiny attribute-based validator (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Validation groups

A constraint without a groups option belongs to the group named Default. When you call validate($object) only Default constraints run. Giving a constraint its own groups lets one class serve several situations:

PHP
$violations = $validator->validate($registration, null, ['registration']);

The password rules above only run when the registration group is requested. A "change profile" screen can validate the same class without demanding a password. Forms pick groups with the validation_groups option. Two details are worth remembering. First, a constraint listed only in registration does not run for Default; to run both, pass ['Default', 'registration']. Second, there is a GroupSequence feature for running cheap groups first and expensive ones (database lookups) only if the cheap ones passed.

flowchart TB
    C1["NotBlank on username<br/>group: Default"]
    C2["Length(min 8) on plainPassword<br/>group: registration"]
    R1["validate(obj)"] --> C1
    R2["validate(obj, null, ['registration'])"] --> C2
    R3["validate(obj, null, ['Default', 'registration'])"] --> C1
    R3 --> C2

Which constraints run depends on the groups you ask for.

Nested objects and Valid

Constraints on a property of an object are not followed into the object stored there, unless you opt in with #[Assert\Valid]:

PHP
class Order
{
    #[Assert\Valid]
    public Address $shipping;

    /** @var list<OrderLine> */
    #[Assert\Valid]
    #[Assert\Count(min: 1)]
    public array $lines = [];
}

With Valid, the validator descends into Address, and into every element of $lines when it is an array. Property paths grow with the nesting, so an error appears as shipping.city or lines[2].quantity, which is exactly what you need to display the message next to the right input.

Validating arrays and single values

Not everything is an object. Decoded JSON, CSV rows or query parameters are arrays. The Collection constraint validates an array by key:

PHP
$violations = $validator->validate($payload, new Assert\Collection([
    'email' => [new Assert\NotBlank(), new Assert\Email()],
    'age'   => new Assert\Range(min: 18, max: 120),
]));

By default Collection reports a missing key as "This field is missing." and an unexpected key as "This field was not expected."; both can be relaxed with allowMissingFields and allowExtraFields. You can also validate one value on its own, for example $validator->validate($email, new Assert\Email()), which is handy in a command or a service. For arrays the property paths use brackets: [email].

The second stand-in implements that array behaviour with plain closures so you can see missing fields, extra fields and bracketed paths.

PHP Validating an array with a collection (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Real-world habits

  • Put constraints on the class that represents the input (an entity, or better a dedicated DTO), not in controllers.
  • Combine presence and format constraints; never rely on Length or Email to reject empty values.
  • Return validation failures from APIs as HTTP 422 with the property paths, so clients can map messages to fields.
  • Keep expensive checks (uniqueness in the database) in a later group or in a custom constraint, covered in Custom Validation Constraints.
  • Remember that validation is not authorization and not a substitute for database constraints such as unique indexes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does validate() return when the data is invalid?

    The validator returns a list of violations and never throws for bad data. You decide what to do with the list: re-render a form, return 422 and so on.
  2. 2. A property has only #[Assert\Length(min: 3)] and its value is an empty string. What happens?

    Emptiness is the job of NotBlank or NotNull. Length, Email and similar constraints deliberately ignore empty values so you can combine them.
  3. 3. A constraint declares groups: ['registration']. Does it run on a plain validate($object) call?

    Constraints without groups belong to Default, and validate() uses Default unless you pass other groups. Pass ['Default', 'registration'] to run both.
  4. 4. What must you add so the validator checks the constraints of an object stored in a property?

    Validation does not cascade by default. #[Assert\Valid] opts in, and also works for every element of an array of objects.

Summary

  • The Validator component checks objects and arrays against constraints and returns a ConstraintViolationList; it is independent of forms and HTTP.
  • Constraints are usually attributes (#[Assert\NotBlank], #[Assert\Length(...)]) on a class; null and empty strings pass every constraint except NotBlank and NotNull.
  • Groups let one class carry several rule sets; plain validate() runs only Default.
  • #[Assert\Valid] cascades into nested objects and arrays, and violation paths such as lines[2].quantity point at the exact field.
  • Assert\Collection validates arrays by key and reports missing and unexpected fields.

Next up: Custom Validation Constraints.