Callback

Callback

The purpose of the Callback constraint is to create completely custom validation rules and to assign any validation errors to specific fields on your object. If you’re using validation with forms, this means that instead of displaying custom errors at the top of the form, you can display them next to the field they apply to.

This process works by specifying one or more callback methods, each of which will be called during the validation process. Each of those methods can do anything, including creating and assigning validation errors.

Note

A callback method itself doesn’t fail or return any value. Instead, as you’ll see in the example, a callback method has the ability to directly add validator “violations”.

Applies toclass or property/method
Options
ClassSymfony\Component\Validator\Constraints\Callback
ValidatorSymfony\Component\Validator\Constraints\CallbackValidator

Configuration

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Context\ExecutionContextInterface;
    5. class Author
    6. {
    7. /**
    8. * @Assert\Callback
    9. */
    10. public function validate(ExecutionContextInterface $context, $payload)
    11. {
    12. // ...
    13. }
    14. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. constraints:
    4. - Callback: validate
  • 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\Author">
    7. <constraint name="Callback">validate</constraint>
    8. </class>
    9. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. use Symfony\Component\Validator\Mapping\ClassMetadata;
    5. class Author
    6. {
    7. public static function loadValidatorMetadata(ClassMetadata $metadata)
    8. {
    9. $metadata->addConstraint(new Assert\Callback('validate'));
    10. }
    11. public function validate(ExecutionContextInterface $context, $payload)
    12. {
    13. // ...
    14. }
    15. }

The Callback Method

The callback method is passed a special ExecutionContextInterface object. You can set “violations” directly on this object and determine to which field those errors should be attributed:

  1. // ...
  2. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  3. class Author
  4. {
  5. // ...
  6. private $firstName;
  7. public function validate(ExecutionContextInterface $context, $payload)
  8. {
  9. // somehow you have an array of "fake names"
  10. $fakeNames = [/* ... */];
  11. // check if the name is actually a fake name
  12. if (in_array($this->getFirstName(), $fakeNames)) {
  13. $context->buildViolation('This name sounds totally fake!')
  14. ->atPath('firstName')
  15. ->addViolation();
  16. }
  17. }
  18. }

Static Callbacks

You can also use the constraint with static methods. Since static methods don’t have access to the object instance, they receive the object as the first argument:

  1. public static function validate($object, ExecutionContextInterface $context, $payload)
  2. {
  3. // somehow you have an array of "fake names"
  4. $fakeNames = [/* ... */];
  5. // check if the name is actually a fake name
  6. if (in_array($object->getFirstName(), $fakeNames)) {
  7. $context->buildViolation('This name sounds totally fake!')
  8. ->atPath('firstName')
  9. ->addViolation()
  10. ;
  11. }
  12. }

External Callbacks and Closures

If you want to execute a static callback method that is not located in the class of the validated object, you can configure the constraint to invoke an array callable as supported by PHP’s [call_user_func](https://www.php.net/manual/en/function.call-user-func.php "call_user_func") function. Suppose your validation function is Acme\Validator::validate():

  1. namespace Acme;
  2. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  3. class Validator
  4. {
  5. public static function validate($object, ExecutionContextInterface $context, $payload)
  6. {
  7. // ...
  8. }
  9. }

You can then use the following configuration to invoke this validator:

  • Annotations

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Symfony\Component\Validator\Constraints as Assert;
    4. /**
    5. * @Assert\Callback({"Acme\Validator", "validate"})
    6. */
    7. class Author
    8. {
    9. }
  • YAML

    1. # config/validator/validation.yaml
    2. App\Entity\Author:
    3. constraints:
    4. - Callback: [Acme\Validator, validate]
  • 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\Author">
    7. <constraint name="Callback">
    8. <value>Acme\Validator</value>
    9. <value>validate</value>
    10. </constraint>
    11. </class>
    12. </constraint-mapping>
  • PHP

    1. // src/Entity/Author.php
    2. namespace App\Entity;
    3. use Acme\Validator;
    4. use Symfony\Component\Validator\Constraints as Assert;
    5. use Symfony\Component\Validator\Mapping\ClassMetadata;
    6. class Author
    7. {
    8. public static function loadValidatorMetadata(ClassMetadata $metadata)
    9. {
    10. $metadata->addConstraint(new Assert\Callback([
    11. Validator::class,
    12. 'validate',
    13. ]));
    14. }
    15. }

Note

The Callback constraint does not support global callback functions nor is it possible to specify a global function or a service method as callback. To validate using a service, you should create a custom validation constraint and add that new constraint to your class.

When configuring the constraint via PHP, you can also pass a closure to the constructor of the Callback constraint:

  1. // src/Entity/Author.php
  2. namespace App\Entity;
  3. use Symfony\Component\Validator\Constraints as Assert;
  4. use Symfony\Component\Validator\Context\ExecutionContextInterface;
  5. use Symfony\Component\Validator\Mapping\ClassMetadata;
  6. class Author
  7. {
  8. public static function loadValidatorMetadata(ClassMetadata $metadata)
  9. {
  10. $callback = function ($object, ExecutionContextInterface $context, $payload) {
  11. // ...
  12. };
  13. $metadata->addConstraint(new Assert\Callback($callback));
  14. }
  15. }

Warning

Using a Closure together with annotation configuration will disable the annotation cache for that class/property/method because Closure cannot be cached. For best performance, it’s recommended to use a static callback method.

Options

callback

type: string, array or Closure [default option]

The callback option accepts three different formats for specifying the callback method:

  • A string containing the name of a concrete or static method;
  • An array callable with the format ['<Class>', '<method>'];
  • A closure.

Concrete callbacks receive an Symfony\Component\Validator\Context\ExecutionContextInterface instance as only argument.

Static or closure callbacks receive the validated object as the first argument and the Symfony\Component\Validator\Context\ExecutionContextInterface instance as the second argument.

groups

type: array | string

It defines the validation group or groups this constraint belongs to. Read more about validation groups.

payload

type: mixed default: null

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to you.

For example, you may want to use several error levels to present failed constraints differently in the front-end depending on the severity of the error.

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