我有一个 ZF2 表单,出于特定原因我不得不禁用 native 验证器。
然后,当以编程方式向表单添加元素时,我还添加了验证器。
其中一个元素是多选数组。
$form->add( array(
'type' => 'Zend\Form\Element\Select',
'options' => array(
(
'label' => 'few items',
'value_options' => Array
(
'one' => 'one',
'two' => 'two',
'three' => 'three',
'four' => 'four',
)
),
'attributes' => array
(
'multiple' => 'multiple',
'value' => array('two','three'),
'required' => 1,
'id' => 'few_items'
),
'name' => 'few_items'
));
此外,我将添加一个 InArray 验证器:
if($f instanceof \Zend\Form\Element\Select){
$inputFilter->add($factory->createInput(array(
'name' => $f->getName(),
'required' => $f->getAttribute('required') == 1,
'validators' => array(
array(
'name' => 'InArray',
'options' => array(
'haystack' => $f->getValueOptions(),
'messages' => array(
InArray::NOT_IN_ARRAY => 'Please select an option',
),
),
),
),
)));
}
问题是验证器总是失败,因为在 POST 多选字段中将返回一个数组,实际上在 InArray 验证器内部查看,它使用 in_array(...) PHP 函数,它不适合这个 - array_intersect 会做技巧,但在编写我自己的验证器之前,我确实有一种感觉,这个轮子已经被发明出来了!
环顾四周,我发现有一个错误引发了这种影响(http://framework.zend.com/issues/browse/ZF2-413),解决方案是引入 Explode 验证器,但我不确定如何将它添加到我的输入过滤器中。
感谢您的建议。
最佳答案
实际上,按照错误修复链接,我想出了如何进行验证。分解验证器将分解值并对每个部分应用验证器:
if($f instanceof \Zend\Form\Element\Select){
$inputFilter->add($factory->createInput(array(
'name' => $f->getName(),
'required' => $f->getAttribute('required') == 1,
'validators' => array(
array(
'name' => 'Explode',
'options' => array(
'validator' => new InArray(array(
'haystack' => $f->getValueOptions(),
'valueDelimeter' => null,
'messages' => array(
InArray::NOT_IN_ARRAY => 'Please select an option',
),
))
)
),
),
)));
}
把这个问题留在这里,因为我自己还没有找到任何其他答案,希望这会在未来帮助人们。
关于php - ZF2 : How do I use InArray validator to validate Multiselect form element?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24805448/