phpzend-framework2zend-inputfilter

How I set the inputFilter to not allow white space in zend framework 2?


How I set the inputFilter to not allow white space in zend framework 2?
I'm trying this:

$inputFilter->add($factory->createInput(array(
            'name'     => 'codigo',
            'required' => true,
            'validators' => array(
                array(
                    'name' => 'not_empty',
                ),
            ),
            'filters' => array(
                 array(
                     'name' => 'Alnum',
                     'allowwhitespace' => false,
                 ),
            ),
        )));

Solution

  • Few points in your code needs minor tweaks;

    Try this:

    $filter = new \Zend\InputFilter\InputFilter();
    $filter->add(array(
                'name'       => 'codigo',
                'required'   => true,
                'validators' => array(
                    array(
                        'name' => 'NotEmpty',
                    ),
                ),
                'filters' => array(
                     array(
                         'name'              => 'Alnum',
                         'options'           => array(
                            'allow_white_space' => false,
                        )
                     ),
                ),
            ));
    
    $filter->setData(['codigo' => 'Whitespace exists']);
    if($filter->isValid() === false) {
        // You'll fall here with a value like multiple spaces etc..
        var_dump($filter->getMessages());
    } else {
        var_dump($filter->getValues()); // Prints ['codigo' => string 'Whitespaceexists']
    }