Purple Hexagon
Purple Hexagon

Reputation: 3578

ZF2 Null Input Filter and Digits Validator

I have a model that implements InputFilterAwareInterface. For one of the fields I wish to validate that user input is digits and use null filter to ensure db field is set to null. Is there a way to do this? The following doesn't work.

        $inputFilter->add(array(
            'name' => '_programme_id',
            'required' => false,
            'allow_empty' => true,
            'validators' => array(
                    array(
                            'name' => 'Digits',
                    )
            ),
            'filters' => array(
                    array(
                            'name' => 'Null',
                            'options' => array(
                                    'type' => 'all'
                            ),
                    )
            ),
        )
    );

Validation fails with message "Invalid type given. String, integer or float expected"

Seems like this is because filtering happens before validation. Is there a quick way to achieve this behaviour?

Upvotes: 2

Views: 2530

Answers (1)

OlegKrivtsov
OlegKrivtsov

Reputation: 750

You can convert your value to integer with the Int filter before passing it to Null filter, as follows:

$inputFilter->add(array(
            'name' => '_programme_id',
            'required' => false,
            'allow_empty' => true,
            'validators' => array(
                    array(
                            'name' => 'Digits',
                    )
            ),
            'filters' => array(
                    array(
                            'name' => 'Int',
                    )
                    array(
                            'name' => 'Null',
                            'options' => array(
                                    'type' => 'all'
                            ),
                    )
            ),
        )
    );

Upvotes: 2

Related Questions