且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Symfony2中基于其他字段值的字段的条件验证

更新时间:2023-11-19 17:18:16

我建议您使用回调验证器



例如,在您的实体类中:

 <?php 

使用Symfony \Component\ Validator \Constraints as Assert;
$ b $ **
* @ Assert\Callback(methods = {myValidation})
* /
class设置{
public function myValidation (ExecutionContextInterface $ context)
{
if(
$ this-> getRadioSelection()=='1'//无线电选择示例
&&
(//检查其他参数
$ this-> getFiled1()== null


{
$ context-> addViolation('mandatory params );
}
//在此放置一些其他验证规则


code $ $ $ $ $ $ $

否则,您可以按照此处所述的方式构建您自己的自定义验证器。一>。



让我知道您需要更多信息。



希望这有助于您。


So here is the scenario: I have a radio button group. Based on their value, I should or shouldn't validate other three fields (are they blank, do they contain numbers, etc).

Can I pass all these values to a constraint somehow, and compare them there?

Or a callback directly in the controller is a better way to solve this?

Generally, what is the best practice in this case?

I suggest you to use a callback validator.

For example, in your entity class:

<?php

use Symfony\Component\Validator\Constraints as Assert;

/**
 * @Assert\Callback(methods={"myValidation"})
 */
class Setting {
    public function myValidation(ExecutionContextInterface $context)
    {
        if (
                $this->getRadioSelection() == '1' // RADIO SELECT EXAMPLE
                &&
                ( // CHECK OTHER PARAMS
                 $this->getFiled1() == null
                )
            )
        {
            $context->addViolation('mandatory params');
        }
       // put some other validation rule here
    }
}

Otherwise you can build your own custom validator as described here.

Let me know you need more info.

Hope this helps.