How to remove a validator from a Form Element / Form Element ValidatorChain in Zend Framework 2?

一个人想着一个人 提交于 2019-11-30 22:01:53

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

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);

Easy ;)

I found this to work with 1.12.3

in my update form

$element = new My_Form_Element_Username('username');
$element->setValue('some-value');
$element->removeValidator('Db_NoRecordExists');
$this->addElement($element);

or

$this->addElement(new My_Form_Element_Username('username')
  ->setValue('some-value')
  ->removeValidator('Db_NoRecordExists');

My_Form_Element_Username just extends some Zend_Form_Element and has the validators defined.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!