【问题标题】:Conditional field validation that depends on another field依赖于另一个字段的条件字段验证
【发布时间】:2013-12-26 15:10:49
【问题描述】:

我需要更改表单中某些字段的验证。验证器是通过一个相当大的 yml 文件配置的。我想知道是否有任何方法可以同时对两个字段进行验证。 就我而言,我有两个不能同时为空的字段。至少要填写一​​个。

不幸的是,到目前为止,我只能看到验证是基于每个字段定义的,而不是多个字段一起定义的。

问题是:是否可以在标准 yml 配置中执行上述验证?

谢谢!

【问题讨论】:

    标签: forms validation symfony


    【解决方案1】:

    我建议你看看Custom validator,尤其是Class Constraint Validator

    我不会复制粘贴整个代码,只是你必须更改的部分。


    扩展Constraint 类。

    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;
        }
    }
    

    通过扩展 ConstraintValidator 类来定义验证器,foobar 是您要检查的 2 个字段:

    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);
            }
        }
    }
    

    使用验证器:

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

    Acme\DemoBundle\Entity\AcmeEntity:
        constraints:
            - Acme\DemoBundle\Validator\Constraints\CheckTwoFields: ~
    

    【讨论】:

    • 感谢您的回答。我没有测试我的代码,很高兴它对你有用!
    • 是否有可能使用 sfValidator 类的解决方案?
    • 我只知道 Symfony2,不知道 Symfony1,对不起。
    • @A.L on public function validatedBy() 记住特定的所有类路径,例如 Acme\DemoBundle\Validator\Constraints\CheckTwoFieldsValidator
    • @Massimo212121 我跟着official documentation,只返回类名。
    猜你喜欢
    • 2015-09-20
    • 2017-04-12
    • 1970-01-01
    • 2019-02-16
    • 1970-01-01
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 2016-05-27
    相关资源
    最近更新 更多