ZF2 not sanitizing input using InputFilter

For programming and general questions on Zend Framework

ZF2 not sanitizing input using InputFilter

Postby wige2480 on Wed Dec 05, 2012 4:03 pm

I am trying to create a single abstract class to manage input validation - in this class I have static functions that return InputFilterInterface objects that I can then add to my interface in the model class that handles the data. However, none of the data ever seems to be validated even though it is valid. I am not using Forms, by the way - the data is coming in via Ajax rather than an HTML form.

Here is my code:

Central Library:

Code: Select all
abastract class InputFilters {
    public static function monthIDFilter($fieldName = 'monthID', $required = FALSE) {
        $factory = new InputFactory();
        return $factory->createInputFilter(array(
            $fieldName => array(
                'name' => $fieldName,
                'required' => $required,
                'validators' => array(
                    array('name' => 'not_empty'),
                    array('name' => 'string_length', 'options' => array(
                        'min'=>'6', 'max'=>'6'
                    array('name' => 'regex', 'options'=>array(
                        'pattern' => '/^[0-9]{6}$/'


Code: Select all
class DataModel implements \Zend\InputFilter\InputFilterAwareInterface {
    protected $_inputFilter;

    public function __construct()

    public function setInputFilter(InputFilterInterface $inputfilter)
        if(!$this->_inputFilter) {
            $this->_inputFilter = new InputFilter();

    public function getInputFilter()
        if(!$this->_inputFilter) {
            $this->_inputFilter = new InputFilter();
        return $this->_inputFilter;

And finally, in the controller:

Code: Select all
public function dataAction()
    $model = new DataModel();
    $inputFilter = $model->getInputFilter();
    if ($inputFilter->isValid()) {
        if ($inputFilter->has('monthID')) {
            echo $inputFilter->getValue('monthID');
            $formMonth = $inputFilter->getValue('monthID');
        } else {
            echo 'nope';
            $formMonth = '';
        $data = $grid->outputData();

In my output, I see the input that contains my monthID (201212) and an array that should be the validation results: Array ( [] => Array ( [monthID] => ) ) and the word 'nope' indicating that the has('monthID') check failed.

Any advice as to where I went wrong? I am very new to ZF2 and I can see a lot of potential in this if I can get it to work, but I'm stumped as to where it is breaking down.
Posts: 8
Joined: Fri Aug 26, 2011 3:28 pm

Return to Zend Framework

Who is online

Users browsing this forum: No registered users and 5 guests