Search code examples
phpvalidationzend-framework2

Use Zend 2 Extension Validator only if file is uploaded


I would like to validate the file extension only if a file is uploaded.

I have a collection of fieldsets that include a File Input element. If I want to upload a file for only one of the fieldsets and leave the rest of the File Input elements empty the form is not validated, although they have required = false. This validation triggers the "fileExtensionNotFound" error.

Is there a way to add the AllowEmpty to or before the Extension validator?

        'file' => array(
            'required' => false,
            'validators' => array(
                array(
                    'name' => 'Zend\Validator\File\Extension',
                    'options' => array(
                        'extension' => array('pdf', 'xls','doc'),
                    )
                )
            )
        )

Solution

  • I had to specify the type to be FileInput.

            'file' => array(
                'type' => '\Zend\InputFilter\FileInput',
                'allow_empty' => true,
                'required' => false,
                'validators' => array(
                    array(
                        'name' => 'Zend\Validator\File\Extension',
                        'options' => array(
                            'extension' => array('pdf', 'xls','doc')
                        ),
                    ),
                ),
            ),