Adding an Input Filter to a ZF2 Form

If you followed the Form Creation in Zend Framework 2 article, you’ll want to know about adding an Input Filter to a ZF2 form.

One way to do this is to define your own input filter class.

This class will reside in the module’s Model/ directory and the input filter will be applied to the form in the controller action method.

The class should implement Zend\InputFilter\InputFilterAwareInterface and should define two methods: setInputFilter() and getInputFilter().

Only getInputFilter() needs to be implemented so we simply throw an exception in setInputFilter().

<?php
namespace Siphor\Model;

use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;

class RegisterForm implements InputFilterAwareInterface
{
    protected $inputFilter;
    
    public function setInputFilter(InputFilterInterface $inputFilter)
    {
        throw new \Exception("Not used");
    }

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

Within getInputFilter(), add your chosen filters and validators. An example below shows the StripTags and StringTrim filters, as well as the isEmpty validator being applied to the first name and last name form fields.

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

        $inputFilter->add(array(
            'name'     => 'first_name',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'NotEmpty',
                    'options' => array(
                        'messages' => array(
                            'isEmpty' => 'First name is required'
                        )
                    )
                )
            )
        ));

        $inputFilter->add(array(
            'name'     => 'last_name',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
             ),
             'validators' => array(
                array(
                    'name' => 'NotEmpty',
                    'options' => array(
                        'messages' => array(
                            'isEmpty' => 'Last name is required'
                        )
                    )
                )
            )
        ));
    }
}

ZF2 provides an EmailAddress validator to validate email addresses. This can be used to validate our ’email’ form input.

$inputFilter->add(array(
    'name'     => 'email',
    'required' => true,
    'filters'  => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim'),
    ),
    'validators' => array(
        array(
        'name' => 'EmailAddress',
            'options' => array(
                'messages' => array(
                    'emailAddressInvalidFormat' => 'Email address format is invalid'
                 )
             )
         ),
         array(
            'name' => 'NotEmpty',
            'options' => array(
                'messages' => array(
                    'isEmpty' => 'Email address is required'
                )
            )
        )
    )
));

As we have a password and password_verify form field, the password_verify field should be used to check if the password entered is an exact match of the password field.

We can therefore use ZF2’s ‘identical’ validator.

$inputFilter->add(array(
    'name'     => 'password',
    'required' => true,
    'filters'  => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim'),
    ),
    'validators' => array(
        array(
            'name' => 'StringLength',
            'options' => array(
                'min' => 8
            )
         )
     )
));

$inputFilter->add(array(
    'name'     => 'password_verify',
    'filters'  => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim'),
    ),
    'validators' => array(
        array(
            'name' => 'identical',
            'options' => array(
                'token' => 'password'
            )
        ),
    )
));

The full getInputFilter() method might look something like the following.

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

        $inputFilter->add(array(
            'name'     => 'first_name',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'NotEmpty',
                    'options' => array(
                        'messages' => array(
                            'isEmpty' => 'First name is required'
                        )
                    )
                )
            )
        ));

        $inputFilter->add(array(
            'name'     => 'last_name',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'NotEmpty',
                    'options' => array(
                        'messages' => array(
                            'isEmpty' => 'Last name is required'
                        )
                    )
                )
            )
        ));

        $inputFilter->add(array(
            'name'     => 'email',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'EmailAddress',
                    'options' => array(
                        'messages' => array(
                            'emailAddressInvalidFormat' => 'Email address format is invalid'
                        )
                    )
                ),
                array(
                    'name' => 'NotEmpty',
                    'options' => array(
                        'messages' => array(
                            'isEmpty' => 'Email address is required'
                        )
                    )
                )
            )
        ));

        $inputFilter->add(array(
            'name'     => 'password',
            'required' => true,
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'StringLength',
                    'options' => array(
                        'min' => 8
                    )
                )
            )
        ));

        $inputFilter->add(array(
            'name'     => 'password_verify',
            'filters'  => array(
                array('name' => 'StripTags'),
                array('name' => 'StringTrim'),
            ),
            'validators' => array(
                array(
                    'name' => 'identical',
                    'options' => array(
                        'token' => 'password'
                    )
                ),
            )
        ));

        $this->inputFilter = $inputFilter;
    }

    return $this->inputFilter;
}

Within the IndexController’s action method, after instantiating the form class, you can set the form’s input filter by using the setInputFilter() method of the form class.

<?php
namespace Siphor\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Siphor\Form\RegisterForm;
use Siphor\Model\RegisterForm as RegisterFormInput;

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $form = new RegisterForm();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $input = new RegisterFormInput();
            $form->setInputFilter($input->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()) {
                print_r($form->getData()); exit();
            }
        }
        return array('form' => $form);
    }
}

If you refresh the web page with your form on, you’ll be able to test the form validation.

Adding an Input Filter to a ZF2 Form

As the code in the IndexController suggests, a valid form will print out the filtered form data. Try testing the form by adding tags or spaces to some of the input fields and you should see the unwanted elements filtered out when viewing the printed form data array.

Note: This article is based on ZF version 2.4.