Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 62 ยท Forms and Validation

Custom Validation Constraints

Build your own Symfony constraint: the Constraint class, the ConstraintValidator, validators that are services, class constraints and callbacks, with stand-ins.

The built-in constraints cover the common cases, but every real project grows rules of its own: a username must not be reserved, a coupon code must exist and be unexpired, an end date must come after the start date. You could write that logic in a controller, but then it would only protect one entry point. A custom constraint packages the rule so it can be attached with an attribute anywhere, reused by forms and APIs, and tested on its own.

A custom constraint is always two classes with a clear division of work. The constraint is the description: it carries the options and the error message. The validator is the behaviour: it receives a value and decides whether it is acceptable. This lesson builds both, shows how a validator can be a service with dependencies, and covers two lighter alternatives (callbacks and class constraints).

The constraint and its validator

By default Symfony finds the validator by appending Validator to the constraint's class name. So ContainsNoReservedWord is checked by ContainsNoReservedWordValidator:

PHP
<?php

namespace App\Validator;

use Symfony\Component\Validator\Constraint;

#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD)]
class ContainsNoReservedWord extends Constraint
{
    public string $message = 'The value "{{ value }}" is reserved.';

    public function __construct(
        public array $words = ['admin', 'root'],
        ?string $message = null,
        ?array $groups = null,
        mixed $payload = null,
    ) {
        parent::__construct([], $groups, $payload);
        $this->message = $message ?? $this->message;
    }
}
PHP
<?php

namespace App\Validator;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Exception\UnexpectedTypeException;
use Symfony\Component\Validator\Exception\UnexpectedValueException;

class ContainsNoReservedWordValidator extends ConstraintValidator
{
    public function validate(mixed $value, Constraint $constraint): void
    {
        if (!$constraint instanceof ContainsNoReservedWord) {
            throw new UnexpectedTypeException($constraint, ContainsNoReservedWord::class);
        }

        if (null === $value || '' === $value) {
            return; // leave emptiness to NotBlank
        }

        if (!is_string($value)) {
            throw new UnexpectedValueException($value, 'string');
        }

        if (in_array(strtolower($value), $constraint->words, true)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $value)
                ->addViolation();
        }
    }
}

Notice four habits. The validator first checks that it received the matching constraint class (a cheap safety net against misconfiguration). It returns early for null and empty strings, so the constraint composes with NotBlank. It throws UnexpectedValueException for a wrong type, because passing an array to a string rule is a programming error, not a user error. And it reports problems through $this->context->buildViolation(...), the only way a validator says "invalid". The constraint then reads like any built-in one:

PHP
#[ContainsNoReservedWord(words: ['admin', 'root', 'support'])]
private string $username;

The real component is not available on this site, so this stand-in implements the same contract in plain PHP: a Constraint, a ConstraintValidator with an execution context that has buildViolation(), and a validator that locates validators by class name.

sequenceDiagram
    participant App as Your code
    participant V as Validator
    participant C as ContainsNoReservedWord
    participant CV as ContainsNoReservedWordValidator
    App->>V: validate(object)
    V->>C: read constraint from attribute
    V->>CV: validate(value, constraint)
    CV-->>V: buildViolation(...)->addViolation()
    V-->>App: list of violations

The validator class is found from the constraint class name; it reports problems through the execution context.

PHP A constraint and its 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.

Validators that are services

A validator is allowed to have dependencies. Symfony registers classes that extend ConstraintValidator as services with the validator.constraint_validator tag (through autoconfiguration), so ordinary constructor autowiring works. This is how a "unique e-mail" rule can ask the database:

PHP
<?php

namespace App\Validator;

use App\Repository\UserRepository;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class UniqueEmailValidator extends ConstraintValidator
{
    public function __construct(private UserRepository $users) {}

    public function validate(mixed $value, Constraint $constraint): void
    {
        if (!$constraint instanceof UniqueEmail || null === $value || '' === $value) {
            return;
        }

        if ($this->users->findOneBy(['email' => $value]) !== null) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ email }}', $value)
                ->addViolation();
        }
    }
}

If the validator service id differs from the class name, the constraint overrides validatedBy() to return that id. In practice you rarely write this particular rule yourself: the Doctrine bridge ships #[UniqueEntity('email')] for exactly this purpose, which you will meet in Entities and Mapping. Writing your own is still the right tool for rules that involve a repository, an API client or a clock. Mind the cost: a validator that queries the database runs on every validation, so put such constraints in a later group (see the sequence tip in Validation).

Class constraints and callbacks

Some rules involve several properties, such as "the end date must be after the start date". A constraint can then target the class instead of a property by returning self::CLASS_CONSTRAINT from getTargets(); its validator receives the whole object as $value.

For one-off rules a full constraint pair is overkill. The Callback constraint points at a method on the object itself:

PHP
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Validator\Context\ExecutionContextInterface;

class Booking
{
    public \DateTimeImmutable $start;
    public \DateTimeImmutable $end;

    #[Assert\Callback]
    public function validateDates(ExecutionContextInterface $context, mixed $payload): void
    {
        if ($this->end <= $this->start) {
            $context->buildViolation('The end must be after the start.')
                ->atPath('end')
                ->addViolation();
        }
    }
}

atPath('end') attaches the message to one field, which is what a form needs to show the error next to the right input. Without it, the violation belongs to the object as a whole. The rule of thumb: use a callback for a rule that only one class needs, a property constraint for a rule you will reuse, and a class constraint for a reusable rule that spans several fields. When a bundle of existing constraints always travels together (say NotBlank, Length and Regex for a postcode), a compound constraint extends Compound and returns that list from getConstraints(), with no validator class at all.

The second stand-in shows a service validator receiving a dependency through its constructor, plus a callback and a class-level rule, all reporting to the same kind of context.

PHP A service validator, a callback and a class rule (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.

Testing a validator

Because a validator is just a class, you can test it without booting the kernel. The framework supplies ConstraintValidatorTestCase, which gives you a mock execution context and assertions such as assertNoViolation() and buildViolation(...)->setParameter(...)->assertRaised(). Test the three standard paths: a valid value, an invalid value with the exact message, and the empty value that must be ignored.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Symfony locate the validator for a constraint class named App\Validator\StrongPassword?

    The default validatedBy() returns the constraint class name plus Validator. Override validatedBy() to point at a service id instead.
  2. 2. Why should a custom validator return early for null and empty strings?

    Built-in constraints follow this convention. It lets you combine a presence rule with a format rule without duplicate messages.
  3. 3. When is a Callback constraint the best choice?

    A callback keeps a single-class rule next to the data. Reusable rules deserve their own constraint and validator.
  4. 4. Which call attaches a violation to the end field instead of the whole object?

    buildViolation() returns a builder. atPath() sets the property path and addViolation() records it.

Summary

  • A custom rule is a constraint (options and message) plus a validator (the logic), found by appending Validator to the constraint's class name.
  • Validators check the constraint type, ignore empty values, throw for wrong types and report through $this->context->buildViolation().
  • Validators are services, so they can depend on repositories, clients or clocks through autowiring.
  • Use callbacks for one-class rules, class constraints for reusable multi-field rules and compound constraints to bundle existing ones.
  • ConstraintValidatorTestCase tests validators without the kernel.

Next up: File Uploads.