@@ -174,11 +174,12 @@ Options
174174``expression ``
175175~~~~~~~~~~~~~~
176176
177- **type **: ``string ``
177+ **type **: ``string|Closure ``
178178
179- The condition written with the expression language syntax that will be evaluated.
180- If the expression evaluates to a falsey value (i.e. using ``== ``, not ``=== ``),
181- validation of constraints won't be triggered.
179+ The condition as a closure or written with the expression language syntax
180+ that will be evaluated. If the closure return value or the evaluated expression
181+ is a falsey value (i.e. using ``== ``, not ``=== ``), validation of constraints won't
182+ be triggered, and constraints of the ``otherwise `` option will, if provided.
182183
183184To learn more about the expression language syntax, see
184185:doc: `/reference/formats/expression_language `.
@@ -200,6 +201,13 @@ in your expression:
200201
201202 The ``context `` variable in expressions was introduced in Symfony 7.2.
202203
204+ When using a closure, the first argument is the object being validated.
205+
206+ .. versionadded :: 7.3
207+
208+ The support for closure in the ``expression `` option was introduced in Symfony 7.3
209+ and requires PHP 8.5.
210+
203211The ``value `` variable can be used when you want to execute more complex
204212validation based on its value:
205213
@@ -215,11 +223,20 @@ validation based on its value:
215223
216224 class Discount
217225 {
226+ // either using an expression...
218227 #[Assert\When(
219228 expression: 'value == "percent"',
220229 constraints: [new Assert\Callback('doComplexValidation')],
221230 )]
231+ // ... or using a closure
232+ #[Assert\When(
233+ expression: static function (Discount $discount) {
234+ return $discount->getType() === 'percent';
235+ },
236+ constraints: [new Assert\Callback('doComplexValidation')],
237+ )]
222238 private ?string $type;
239+
223240 // ...
224241
225242 public function doComplexValidation(ExecutionContextInterface $context, $payload): void
0 commit comments