How to use InputFilter without form class in Zend framework 2
Asked Answered
L

1

8

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?

Ladoga answered 18/11, 2012 at 21:48 Comment(0)
S
17

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();
    /* ... */
}
Sextet answered 18/11, 2012 at 22:36 Comment(2)
Can you suggest an approach to validate only one row from set?Ladoga
@yurisnk You can set list of fields to validate in call to setValidationGroup(), just use ->setValidationGroup('field_name') for single field or ->setValidationGroup(array('field_name1', 'field_name2')) for set of fields in above example.Sextet

© 2022 - 2024 — McMap. All rights reserved.