在Symfony2中基于其他字段值的字段的条件验证 [英] Conditional validation of fields based on other field value in Symfony2
问题描述
我可以将所有这些值传递给一个约束不知何故,并在那里比较它们?
或者直接在控制器中直接回调是解决这个问题的更好方法吗?
一般来说,在这种情况下最好的做法是什么?
我建议您使用回调验证器。
例如,在您的实体类中:
<?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.
这篇关于在Symfony2中基于其他字段值的字段的条件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!