|
| 1 | +.. index:: |
| 2 | + single: Validation; Callables |
| 3 | + |
| 4 | +How to Use Validation Constraints in Callable Validation (Validation Callables) |
| 5 | +=============================================================================== |
| 6 | + |
| 7 | +Sometimes you need to reuse Symfony's constraints in places like the :doc:`Console Component </components/console>`, |
| 8 | +to validate the answer to a console question. ``Validation::createCallable()`` |
| 9 | +can be used to create a callable based on the given constraints:: |
| 10 | + |
| 11 | + use Symfony\Component\Console\Style\SymfonyStyle; |
| 12 | + use Symfony\Component\Validator\Constraints\NotNull; |
| 13 | + use Symfony\Component\Validator\Validation; |
| 14 | + |
| 15 | + $io = new SymfonyStyle($input, $output); |
| 16 | + $validation = Validation::createCallable(new NotBlank()); |
| 17 | + |
| 18 | + $wsdl = $io->ask('Wsdl location URL', null, $validation); |
| 19 | + |
| 20 | +The argument of ``createCallable()`` is variadic, so you can pass any number of constraints:: |
| 21 | + |
| 22 | + // ... |
| 23 | + use Symfony\Component\Validator\Constraints\Length; |
| 24 | + use Symfony\Component\Validator\Constraints\Url; |
| 25 | + |
| 26 | + $validation = Validation::createCallable(new Length(['max' => 255]), new Url()); |
| 27 | + |
| 28 | +.. versionadded:: 5.1 |
| 29 | + |
| 30 | + ``Validation::createCallable()`` was introduced in Symfony 5.1. |
| 31 | + |
| 32 | +The callable throws a ``ValidationFailedException`` if the validation failed. |
| 33 | +Use ``createValidCallable()`` if you want to use the callable in places like |
| 34 | +:doc:`OptionsResolver Component </components/options_resolver>` where booleans are expected:: |
| 35 | + |
| 36 | + use Symfony\Component\OptionsResolver\OptionsResolver; |
| 37 | + use Symfony\Component\Validator\Validation; |
| 38 | + |
| 39 | + $resolver = new OptionsResolver(); |
| 40 | + $resolver->setAllowedValues('name', Validation::createValidCallable( |
| 41 | + new Assert\Length(['min' => 10 ]) |
| 42 | + )); |
| 43 | + |
| 44 | +.. versionadded:: 5.3 |
| 45 | + |
| 46 | + ``Validation::createValidCallable()`` was introduced in Symfony 5.3. |
0 commit comments