phpvalidationzend-framework2input-filter

Empty values passed to Zend framework 2 validators


How can I pass an empty value through Zend framework 2 ValidatorChain to my custom validator?

It was possible on ZF1 by allowEmpty(false)

On ZF2 with empty element value :


Solution

  • Following works for ZF2 version 2.1.1:

    The problem (if I got it correctly) is that in following example, for empty values of 'fieldName', no validation is triggered. This can be quite annoying, though in

    $input = new \Zend\InputFilter\Input('fieldName');
    
    $input
        ->setAllowEmpty(true)
        ->setRequired(false)
        ->getValidatorChain()
        ->attach(new \Zend\Validator\Callback(function ($value) {
            echo 'called validator!';
    
            return true; // valid
        }));
    
    $inputFilter = new \Zend\InputFilter\InputFilter();
    $inputFilter->add($input);
    
    $inputFilter->setData(array('fieldName' => 'value'));
    var_dump($inputFilter->isValid()); // true, echoes 'called validator!'
    
    $inputFilter->setData(array('fieldName' => ''));
    var_dump($inputFilter->isValid()); // true, no output
    
    $inputFilter->setData(array());
    var_dump($inputFilter->isValid()); // true, no output
    

    This is quite annoying when you have particular cases, like checking an URL assigned to a page in your CMS and avoiding collisions (empty URL is still an URL!).

    There's a way of handling this for empty strings, which is to basically attach the NotEmpty validator on your own, and avoiding calls to setRequired and setAllowEmpty. This will basically tell Zend\InputFilter\Input#injectNotEmptyValidator not to utomatically attach a NotEmpty validator on its own:

    $input = new \Zend\InputFilter\Input('fieldName');
    
    $input
        ->getValidatorChain()
        ->attach(new \Zend\Validator\NotEmpty(\Zend\Validator\NotEmpty::NULL))
        ->attach(new \Zend\Validator\Callback(function ($value) {
            echo 'called validator!';
    
            return true; // valid
        }));
    
    $inputFilter = new \Zend\InputFilter\InputFilter();
    $inputFilter->add($input);
    
    $inputFilter->setData(array('fieldName' => 'value'));
    var_dump($inputFilter->isValid()); // true, echoes 'called validator!'
    
    $inputFilter->setData(array('fieldName' => ''));
    var_dump($inputFilter->isValid()); // true, echoes 'called validator!'
    
    $inputFilter->setData(array());
    var_dump($inputFilter->isValid()); // false (null was passed to the validator)
    

    If you also want to check against null, you will need to extend Zend\InputFilter\Input as following:

    class MyInput extends \Zend\InputFilter\Input
    {
        // disabling auto-injection of the `NotEmpty` validator
        protected function injectNotEmptyValidator() {}
    }