依赖于另一个字段的条件字段验证 [英] Conditional field validation that depends on another field

查看:33
本文介绍了依赖于另一个字段的条件字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

谢谢!

推荐答案

我建议你看看 自定义验证器,尤其是 Class约束验证器.

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.

扩展 Constraint 类.

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

<?php

namespace AcmeDemoBundleValidatorConstraints;

use SymfonyComponentValidatorConstraint;

/**
 * @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 个字段:

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

use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintValidator;

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

AcmeDemoBundleEntityAcmeEntity:
    constraints:
        - AcmeDemoBundleValidatorConstraintsCheckTwoFields: ~

这篇关于依赖于另一个字段的条件字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆