Skip to content

How to Create a custom Validation Constraint

Warning: You are browsing the documentation for Symfony 2.x, which is no longer maintained.

Read the updated version of this page for Symfony 7.1 (the current stable version).

You can create a custom constraint by extending the base constraint class, Constraint. As an example you're going to create a simple validator that checks if a string contains only alphanumeric characters.

Creating the Constraint Class

First you need to create a Constraint class and extend Constraint:

1
2
3
4
5
6
7
8
9
10
11
12
// src/AppBundle/Validator/Constraints/ContainsAlphanumeric.php
namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class ContainsAlphanumeric extends Constraint
{
    public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
}

Note

The @Annotation annotation is necessary for this new constraint in order to make it available for use in classes via annotations. Options for your constraint are represented as public properties on the constraint class.

Creating the Validator itself

As you can see, a constraint class is fairly minimal. The actual validation is performed by another "constraint validator" class. The constraint validator class is specified by the constraint's validatedBy() method, which includes some simple default logic:

1
2
3
4
5
// in the base Symfony\Component\Validator\Constraint class
public function validatedBy()
{
    return \get_class($this).'Validator';
}

In other words, if you create a custom Constraint (e.g. MyConstraint), Symfony will automatically look for another class, MyConstraintValidator when actually performing the validation.

The validator class is also simple, and only has one required method validate():

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// src/AppBundle/Validator/Constraints/ContainsAlphanumericValidator.php
namespace AppBundle\Validator\Constraints;

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

class ContainsAlphanumericValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if (!$constraint instanceof ContainsAlphanumeric) {
           throw new UnexpectedTypeException($constraint, ContainsAlphanumeric::class);
        }
        
        // custom constraints should ignore null and empty values to allow
        // other constraints (NotBlank, NotNull, etc.) take care of that
        if (null === $value || '' === $value) {
            return;
        }

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

        if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
            // If you're using the new 2.5 validation API (you probably are!)
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ string }}', $value)
                ->addViolation();

            // If you're using the old 2.4 validation API
            /*
            $this->context->addViolation(
                $constraint->message,
                array('{{ string }}' => $value)
            );
            */
        }
    }
}

Inside validate, you don't need to return a value. Instead, you add violations to the validator's context property and a value will be considered valid if it causes no violations. The buildViolation() method takes the error message as its argument and returns an instance of ConstraintViolationBuilderInterface. The addViolation() method call finally adds the violation to the context.

Using the new Validator

Using custom validators is very easy, just as the ones provided by Symfony itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// src/AppBundle/Entity/AcmeEntity.php
use Symfony\Component\Validator\Constraints as Assert;
use AppBundle\Validator\Constraints as AcmeAssert;

class AcmeEntity
{
    // ...

    /**
     * @Assert\NotBlank
     * @AcmeAssert\ContainsAlphanumeric
     */
    protected $name;

    // ...
}

If your constraint contains options, then they should be public properties on the custom Constraint class you created earlier. These options can be configured like options on core Symfony constraints.

Constraint Validators with Dependencies

If your constraint validator has dependencies, such as a database connection, it will need to be configured as a service in the Dependency Injection Container. This service must include the validator.constraint_validator tag so that the validation system knows about it:

1
2
3
4
5
6
# app/config/services.yml
services:
    app.contains_alphanumeric_validator:
        class: AppBundle\Validator\Constraints\ContainsAlphanumericValidator
        tags:
            - { name: validator.constraint_validator }

Now, when Symfony looks for the ContainsAlphanumericValidator validator, it will load this service from the container.

Note

In earlier versions of Symfony, the tag required an alias key (usually set to the class name). This alias is now optional, but if you define it, your constraint's validatedBy() method must return the same value.

Class Constraint Validator

Beside validating a class property, a constraint can have a class scope by providing a target in its Constraint class:

1
2
3
4
public function getTargets()
{
    return self::CLASS_CONSTRAINT;
}

With this, the validator validate() method gets an object as its first argument:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class ProtocolClassValidator extends ConstraintValidator
{
    public function validate($protocol, Constraint $constraint)
    {
        if ($protocol->getFoo() != $protocol->getBar()) {
            // If you're using the new 2.5 validation API (you probably are!)
            $this->context->buildViolation($constraint->message)
                ->atPath('foo')
                ->addViolation();

            // If you're using the old 2.4 validation API
            /*
            $this->context->addViolationAt(
                'foo',
                $constraint->message,
                array(),
                null
            );
            */
        }
    }
}

Tip

The atPath() method defines the property which the validation error is associated to. Use any valid PropertyAccess syntax to define that property.

Note that a class constraint validator is applied to the class itself, and not to the property:

1
2
3
4
5
6
7
/**
 * @AcmeAssert\ContainsAlphanumeric
 */
class AcmeEntity
{
    // ...
}
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version