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".

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
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

// ...useSymfony\Component\Validator\Context\ExecutionContextInterface;classAuthor{// ...private$firstName;publicfunctionvalidate(ExecutionContextInterface$context,$payload){// somehow you have an array of "fake names"$fakeNames=[/* ... */];// check if the name is actually a fake nameif(in_array($this->getFirstName(),$fakeNames)){$context->buildViolation('This name sounds totally fake!')->atPath('firstName')->addViolation();}}}

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
2
3
4
5
6
7
8
9
10
11
12
13

publicstaticfunctionvalidate($object,ExecutionContextInterface$context,$payload){// somehow you have an array of "fake names"$fakeNames=[/* ... */];// check if the name is actually a fake nameif(in_array($object->getFirstName(),$fakeNames)){$context->buildViolation('This name sounds totally fake!')->atPath('firstName')->addViolation();}}

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 function.
Suppose your validation function is Acme\Validator::validate():

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: