How to Define Conditional Validation in yml

Asked 3 months ago, Updated 3 months ago, 9 views

When defining the form validation function of symfony2 in yml, I would like to make the field B required only if the value of the field A is 1. How do I write such a conditional validation in yml?

Thank you for your cooperation.


2022-09-30 13:58

1 Answers

I think the response method will change depending on where the motivation to make it required is.
If you want to control it on the form (browser side), I think JavaScript should handle it rather than Symfony.

If the field A is a validation error if the field B is empty only if the value of the field A is 1, then you can use Callback.

Yaml side

        - Callback: validate

Entity side

  use Symphony\Component\Validator\Context\ExecutionContextInterface;

  class author 


    public function validate(ExecutionContextInterface$context){
        $context->buildViolation('If you have entered A, be sure to enter B.')


This callback validation gives you the flexibility to validate.

Refer to the Symfony documentation for more information.The information is detailed.

2022-09-30 13:58

If you have any answers or tips

© 2023 OneMinuteCode. All rights reserved.