I found an easy-to-use solution, although I no longer use the form, now I use InputFilter and still need the same stuff. But found an easy solution
AbstractFilterValidator , my own implementation
abstract class AbstractFilterValidator extends AbstractValidator { public function isValid($value) { $this->setValue($value); $filter = $this->buildFilter(); $filter->setData($value); if (!$filter->isValid()) { $this->abstractOptions['messages'] = $filter->getMessages(); return false; } return true; } public function getMessages() { return $this->abstractOptions['messages']; } abstract protected function buildFilter(); }
Old answer
Although you used InputFilterProviderInterface , I used Zend\InputFilter\InputFilter and wanted the same thing as you. If the field set has not been filled, check true .
To do this, I replace isValid following text:
public function isValid() { $values = array_filter($this->getRawValues()); if (empty($values)) { return true; } return parent::isValid(); }
It just filters the array from all the empty keys of the array, see docs for information on this. Then check if $values empty, and if so, return true . Otherwise, validators are called.
Well, I need something else, but I need a decent solution. I still could not find a good one, so I wrote the following code.
<?php namespace Application\InputFilter; use Zend\InputFilter as ZFI; class InputFilter extends ZFI\InputFilter { private $required = true; public function isRequired() { return $this->required; } public function setRequired($required) { $this->required = (bool) $required; return $this; } public function isValid() { if (!$this->isRequired() && empty(array_filter($this->getRawValues()))) { return true; } return parent::isValid(); } }
github gist
Now you can just call setRequired(false) on the InputFilter
source share