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

I read this question on SO: " how to disable inArray validation forms in zend framework2 " and tried to find it, but could not find any way to disconnect / remove the InArray validator. But InArray is only a validator. So, how to remove the validator from the form element validation list?

I can get validators:

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

and maybe then can disable the array element using validator, I want to delete and then pass the array of results back to the input object and to the form element. But it is really dirty and, of course, not recommended.

So how to remove a validator from a form element?

+3
source share
2 answers

Well, you can 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 can 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 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); 

Just;)

+6
source

I found this works from 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 simply extends some Zend_Form_Element and has certain validators.

+1
source

All Articles