Zend Framework 的 2 InputFilter 中有条件地需要 [英] Conditionally required in Zend Framework's 2 InputFilter
问题描述
我正在使用 Zend Framework 2 制作应用程序.我正在使用它的 InputFilter
验证输入.是否有可能有条件地要求一些 Input
?我的意思是我有这样的代码:
I am making an application using Zend Framework 2. I am validating input using it's InputFilter
. Is it possible, to make some Input
s required conditionally? I mean I have code like that:
$filter = new \Zend\InputFilter\InputFilter();
$factory = new \Zend\InputFilter\Factory();
$filter->add($factory->createInput(array(
'name' => 'type',
'required' => true
)));
$filter->add($factory->createInput(array(
'name' => 'smth',
'required' => true
)));
我希望字段 something
是必需的,仅当 type
等于 1
时.有没有内置的方法来做到这一点?还是我应该创建自定义验证器?
I want the field something
, to be required, ONLY when type
is equal 1
. Is there a built-in way to do that? Or should I just create custom validator?
推荐答案
首先,您可能希望从 传递给 Zend 框架 2 验证器的空值
您可以使用回调输入过滤器,如下例所示:
You can use a callback input filter as in following example:
$filter = new \Zend\InputFilter\InputFilter();
$type = new \Zend\InputFilter\Input('type');
$smth = new \Zend\InputFilter\Input('smth');
$smth
->getValidatorChain()
->attach(new \Zend\Validator\NotEmpty(\Zend\Validator\NotEmpty::NULL))
->attach(new \Zend\Validator\Callback(function ($value) use ($type) {
return $value || (1 != $type->getValue());
}));
$filter->add($type);
$filter->add($smth);
当 smth
的值是一个空字符串并且 type
的值不是 1
时,这基本上会起作用.如果 type
的值为 1
,则 smth
必须与空字符串不同.
This will basically work when the value smth
is an empty string and the value for type
is not 1
. If the value for type
is 1
, then smth
has to be different from an empty string.
这篇关于Zend Framework 的 2 InputFilter 中有条件地需要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!