validationzend-framework2zend-inputfilter

How to use InputFilter without form class in Zend framework 2


My model object implements InputFilterAwareInterface and have getInputFilter() method, that returned Zend\InputFilter\InputFilter instance

I don't need form in my case, I just need validate elements from array. How I can use Zend\InputFilter\InputFilter for validating data from array without creating form class?


Solution

  • Hope the code is self-explanatory (setData to set your array, setValidationGroup to check all elements, and isValid to get result of validation):

    use \Zend\InputFilter\InputFilterInterface;
    
    /* ... */
    
    /** @var $data array */
    
    /** @var $filter InputFilterInterface */
    $filter = $this->getInputFilter();
    
    $isValid = $filter->setData($data)
                      ->setValidationGroup(InputFilterInterface::VALIDATE_ALL)
                      ->isValid();
    
    if (!$isValid)
    {
        $errorMessages = $filter->getMessages();
        /* ... */
    }