Skip to main content
Blue Moose logo Blue Moose Field notes
← All articles
code

Custom Symfony constraint with injected services

Laptop screen showing source code on a desk

Last month a signup form on one of my side projects let two people register with the same email address, because the "is this email taken?" check lived in a controller and the CSV import path skipped the controller entirely. Uniqueness rules belong next to the validation layer, not scattered across entry points. Symfony's Validator makes that easy: a custom constraint is two small classes, and the validator half can take services through normal dependency injection.

The constraint: configuration only

The constraint class carries the message and any options, nothing else. Following the custom constraint docs, every option goes through the constructor so it works as a PHP attribute.

<?php

namespace App\Validator;

use Symfony\Component\Validator\Constraint;

#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD)]
class UnusedEmail extends Constraint
{
    public string $message = 'The email "{{ email }}" is already registered.';

    public function __construct(?string $message = null, ?array $groups = null, $payload = null)
    {
        $this->message = $message ?? $this->message;

        parent::__construct(null, $groups, $payload);
    }
}

There is no validatedBy() override: by default Symfony looks for a class named after the constraint plus Validator, here UnusedEmailValidator.

The validator: where the dependency goes

With the default services.yaml autoconfiguration, the validator is tagged validator.constraint_validator automatically, so I can inject whatever I like. I hide the lookup behind a tiny interface so the validator does not care whether the data comes from Doctrine, an API or a file.

<?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;

interface AccountLookup
{
    public function emailExists(string $email): bool;
}

class UnusedEmailValidator extends ConstraintValidator
{
    public function __construct(private readonly AccountLookup $accounts)
    {
    }

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

        // Leave null and '' to NotBlank/NotNull.
        if (null === $value || '' === $value) {
            return;
        }

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

        if ($this->accounts->emailExists(strtolower($value))) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ email }}', $value)
                ->addViolation();
        }
    }
}

In a real project the interface lives in its own file (PSR-4 wants one class per file); I inlined it here for readability. Three details matter. The instanceof guard catches a constraint wired to the wrong validator. Skipping null and empty values keeps the rules composable. And the UnexpectedValueException turns a wrong type into a validation failure instead of a fatal error.

Using it, and testing it

Stack it with built-in constraints on a DTO. Order matters little, since each constraint reports independently.

use Symfony\Component\Validator\Constraints as Assert;

final class RegistrationInput
{
    #[Assert\NotBlank]
    #[Assert\Email]
    #[UnusedEmail]
    public ?string $email = null;
}

For tests, Symfony ships ConstraintValidatorTestCase, which builds the validator through createValidator() so I can hand it a stub lookup.

use Symfony\Component\Validator\Test\ConstraintValidatorTestCase;

final class UnusedEmailValidatorTest extends ConstraintValidatorTestCase
{
    protected function createValidator(): UnusedEmailValidator
    {
        return new UnusedEmailValidator(new class implements AccountLookup {
            public function emailExists(string $email): bool
            {
                return 'taken@example.com' === $email;
            }
        });
    }

    public function testFreeEmailPasses(): void
    {
        $this->validator->validate('free@example.com', new UnusedEmail());

        $this->assertNoViolation();
    }

    public function testTakenEmailFails(): void
    {
        $this->validator->validate('Taken@Example.com', new UnusedEmail());

        $this->buildViolation('The email "{{ email }}" is already registered.')
            ->setParameter('{{ email }}', 'Taken@Example.com')
            ->assertRaised();
    }
}

I traced these by hand rather than running them, so treat them as a starting point and run them in your own suite.

When to use it, and the catch

This pays off once the same rule has two or more entry points: a form, an API payload, an import command. It is overkill for a one-off check. The gotcha is that a validator-level uniqueness check is a courtesy, not a guarantee. Two concurrent requests can both pass it, so keep the unique index in the database and treat the constraint as the friendly error message in front of it.

BM
Blue Moose
The moose behind Blue Moose. Full-stack PHP developer — Drupal by day, Symfony by night, tests always.