如何从Zend Framework 2中的表单元素/表单元素ValidatorChain中删除验证器? [英] How to remove a validator from a Form Element / Form Element ValidatorChain in Zend Framework 2?

查看:90
本文介绍了如何从Zend Framework 2中的表单元素/表单元素ValidatorChain中删除验证器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在SO上阅读了以下问题:"如何在zend framework2中禁用inArray验证器表单",并试图找到它,但找不到任何方法来分离/删除InArray验证程序.但是InArray只是 a 验证器.那么如何从表单元素的验证器列表中删除验证器?

I read this question on SO: "how to disable inArray validator forms in zend framework2" and was trying to find it out, but couldn't find any way to detach/remove the InArray Validator. But InArray is just a validator. So how can remove a validator from the validator list of a form element?

我可以得到验证器:

$myElement = $form->getInputFilter()->get('city');
$validatorChain = $cityElement->getValidatorChain();
$validators = $validatorChain->getValidators();

,然后可以使用验证器取消设置数组元素,我想删除该数组元素,然后将结果数组传递回Input对象和form元素.但这确实很脏,肯定不是推荐的方法.

and maybe can then unset the array element with the validator, I want to remove, and then pass the result array back to the Input object and to the form element. But it's really dirty and surely not the recommended way.

那么如何从表单元素中删除验证器?

So how to remove a validator from a form element?

推荐答案

好吧,您可以将验证器链替换为新的验证器链.假设我有一个带有两个验证器的元素:

Well, you could just replace the validator chain with a new one. Let's say I have an element with two validators:

  • Zend \ Validator \ NotEmpty
  • Zend \ Validator \ EmailAddress

我想从中删除EmailAddress验证器.您可以执行以下操作:

And I want to remove the EmailAddress validator from it. You could do something like this:

// create new validator chain
$newValidatorChain = new \Zend\Validator\ValidatorChain;
// loop through all validators of the validator chained currently attached to the element
foreach ($form->getInputFilter()->get('myElement')->getValidatorChain()->getValidators() as $validator) {
    // attach validator unless it's instance of Zend\Validator\EmailAddress
    if (!($validator['instance'] instanceof \Zend\Validator\EmailAddress)) {
        $newValidatorChain->addValidator($validator['instance'], $validator['breakChainOnFailure']);
    }
}
// replace the old validator chain on the element
$form->getInputFilter()->get('myElement')->setValidatorChain($newValidatorChain);

容易;)

这篇关于如何从Zend Framework 2中的表单元素/表单元素ValidatorChain中删除验证器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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