Conditional field validation that depends on another field

前端 未结 1 1353
再見小時候
再見小時候 2020-12-01 22:50

I need to change the validation of some field in a form. The validator is configured via a quite large yml file. I wonder if there is any way to do validation on two fields

相关标签:
1条回答
  • 2020-12-01 23:33

    I suggest you to look at Custom validator, especially Class Constraint Validator.

    I won't copy paste the whole code, just the parts which you will have to change.


    Extends the Constraint class.

    src/Acme/DemoBundle/Validator/Constraints/CheckTwoFields.php

    <?php
    
    namespace Acme\DemoBundle\Validator\Constraints;
    
    use Symfony\Component\Validator\Constraint;
    
    /**
     * @Annotation
     */
    class CheckTwoFields extends Constraint
    {
        public $message = 'You must fill the foo or bar field.';
    
        public function validatedBy()
        {
                return 'CheckTwoFieldsValidator';
        }
    
        public function getTargets()
        {
                return self::CLASS_CONSTRAINT;
        }
    }
    

    Define the validator by extending the ConstraintValidator class, foo and bar are the 2 fields you want to check:

    src/Acme/DemoBundle/Validator/Constraints/CheckTwoFieldsValidator.php

    namespace Acme\DemoBundle\Validator\Constraints;
    
    use Symfony\Component\Validator\Constraint;
    use Symfony\Component\Validator\ConstraintValidator;
    
    class CheckTwoFieldsValidator extends ConstraintValidator
    {
        public function validate($protocol, Constraint $constraint)
        {
            if ((empty($protocol->getFoo())) && (empty($protocol->getBar()))) {
                $this->context->addViolationAt('foo', $constraint->message, array(), null);
            }
        }
    }
    

    Use the validator:

    src/Acme/DemoBundle/Resources/config/validation.yml

    Acme\DemoBundle\Entity\AcmeEntity:
        constraints:
            - Acme\DemoBundle\Validator\Constraints\CheckTwoFields: ~
    
    0 讨论(0)
提交回复
热议问题