How to Create a Custom Validation Constraint

How to Create a Custom Validation Constraint

You can create a custom constraint by extending the base constraint class, Symfony\Component\Validator\Constraint. As an example you’re going to create a basic validator that checks if a string contains only alphanumeric characters.

Creating the Constraint Class

First you need to create a Constraint class and extend Symfony\Component\Validator\Constraint:

  1. // src/Validator/ContainsAlphanumeric.php
  2. namespace App\Validator;
  3. use Symfony\Component\Validator\Constraint;
  4. /**
  5. * @Annotation
  6. */
  7. class ContainsAlphanumeric extends Constraint
  8. {
  9. public $message = 'The string "{{ string }}" contains an illegal character: it can only contain letters or numbers.';
  10. }

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 has this default logic:

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

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 only has one required method validate():

  1. // src/Validator/ContainsAlphanumericValidator.php
  2. namespace App\Validator;
  3. use Symfony\Component\Validator\Constraint;
  4. use Symfony\Component\Validator\ConstraintValidator;
  5. use Symfony\Component\Validator\Exception\UnexpectedTypeException;
  6. use Symfony\Component\Validator\Exception\UnexpectedValueException;
  7. class ContainsAlphanumericValidator extends ConstraintValidator
  8. {
  9. public function validate($value, Constraint $constraint)
  10. {
  11. if (!$constraint instanceof ContainsAlphanumeric) {
  12. throw new UnexpectedTypeException($constraint, ContainsAlphanumeric::class);
  13. }
  14. // custom constraints should ignore null and empty values to allow
  15. // other constraints (NotBlank, NotNull, etc.) to take care of that
  16. if (null === $value || '' === $value) {
  17. return;
  18. }
  19. if (!is_string($value)) {
  20. // throw this exception if your validator cannot handle the passed type so that it can be marked as invalid
  21. throw new UnexpectedValueException($value, 'string');
  22. // separate multiple types using pipes
  23. // throw new UnexpectedValueException($value, 'string|int');
  24. }
  25. if (!preg_match('/^[a-zA-Z0-9]+$/', $value, $matches)) {
  26. // the argument must be a string or an object implementing __toString()
  27. $this->context->buildViolation($constraint->message)
  28. ->setParameter('{{ string }}', $value)
  29. ->addViolation();
  30. }
  31. }
  32. }

New in version 4.4: The feature to allow passing an object as the buildViolation() argument was introduced in Symfony 4.4.

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 Symfony\Component\Validator\Violation\ConstraintViolationBuilderInterface. The addViolation() method call finally adds the violation to the context.

Using the new Validator

You can use custom validators like the ones provided by Symfony itself:

  • Annotations

    1. // src/Entity/AcmeEntity.php
    2. namespace App\Entity;
    3. use App\Validator as AcmeAssert;
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. class AcmeEntity
    6. {
    7. // ...
    8. /**
    9. * @Assert\NotBlank
    10. * @AcmeAssert\ContainsAlphanumeric
    11. */
    12. protected $name;
    13. // ...
    14. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\AcmeEntity:
    3. properties:
    4. name:
    5. - NotBlank: ~
    6. - App\Validator\ContainsAlphanumeric: ~
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping https://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
    6. <class name="App\Entity\AcmeEntity">
    7. <property name="name">
    8. <constraint name="NotBlank"/>
    9. <constraint name="App\Validator\ContainsAlphanumeric"/>
    10. </property>
    11. </class>
    12. </constraint-mapping>
  • PHP

    1. // src/Entity/AcmeEntity.php
    2. namespace App\Entity;
    3. use App\Validator\ContainsAlphanumeric;
    4. use Symfony\Component\Validator\Constraints\NotBlank;
    5. use Symfony\Component\Validator\Mapping\ClassMetadata;
    6. class AcmeEntity
    7. {
    8. public $name;
    9. public static function loadValidatorMetadata(ClassMetadata $metadata)
    10. {
    11. $metadata->addPropertyConstraint('name', new NotBlank());
    12. $metadata->addPropertyConstraint('name', new ContainsAlphanumeric());
    13. }
    14. }

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 you’re using the default services.yaml configuration, then your validator is already registered as a service and tagged with the necessary validator.constraint_validator. This means you can inject services or configuration like any other service.

Class Constraint Validator

Besides validating a single property, a constraint can have an entire class as its scope. You only need to add this to the Constraint class:

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

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

  1. class ProtocolClassValidator extends ConstraintValidator
  2. {
  3. public function validate($protocol, Constraint $constraint)
  4. {
  5. if ($protocol->getFoo() != $protocol->getBar()) {
  6. $this->context->buildViolation($constraint->message)
  7. ->atPath('foo')
  8. ->addViolation();
  9. }
  10. }
  11. }

Tip

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

A class constraint validator is applied to the class itself, and not to the property:

  • Annotations

    1. // src/Entity/AcmeEntity.php
    2. namespace App\Entity;
    3. use App\Validator as AcmeAssert;
    4. /**
    5. * @AcmeAssert\ProtocolClass
    6. */
    7. class AcmeEntity
    8. {
    9. // ...
    10. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\AcmeEntity:
    3. constraints:
    4. - App\Validator\ProtocolClass: ~
  • XML

    1. <!-- config/validator/validation.xml -->
    2. <class name="App\Entity\AcmeEntity">
    3. <constraint name="App\Validator\ProtocolClass"/>
    4. </class>
  • PHP

    1. // src/Entity/AcmeEntity.php
    2. namespace App\Entity;
    3. use App\Validator\ProtocolClass;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class AcmeEntity
    6. {
    7. // ...
    8. public static function loadValidatorMetadata(ClassMetadata $metadata)
    9. {
    10. $metadata->addConstraint(new ProtocolClass());
    11. }
    12. }

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.