Conditional field validation that depends on another field

匿名 (未验证) 提交于 2019-12-03 02:12:02

问题:

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 at once. In my case I have two fields that cannot be both empty. At least one has to be filled.

Unfortunately till now I just could see that the validation are defined on a per-field basis, not on multiple fields together.

The question is: is it possible in the standard yml configurations to perform the aforementioned validation?

thanks!

回答1:

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: ~ 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!