Search code examples
phpzend-framework2zend-framework3

Zend Framework multiple input one validator


I'm designing a form with 3 file upload fields in Zend 2, is it possible to write one validator for 3 fields? I want to use this validator for 3 fields

 $inputFilter->add([
                'type'     => 'Zend\InputFilter\FileInput',
                'name'     => 'foto1',  // Element's name.
                'required' => true,    // Whether the field is required.
                'validators' => [      // Validators.
                    ['name'    => 'FileUploadFile'],
                    [
                        'name'    => 'FileMimeType',                        
                        'options' => [                            
                            'mimeType'  => ['image/jpeg', 'image/png' ]
                        ]
                    ],
                    ['name'    => 'FileIsImage'],
                    [
                        'name'    => 'FileImageSize',
                        'options' => [
                            'minWidth'  => 128,
                            'minHeight' => 128,
                            'maxWidth'  => 4096,
                            'maxHeight' => 4096
                        ]
                    ],
                ],
                'filters'  => [        // Filters.
                    [
                        'name' => 'FileRenameUpload',
                        'options' => [  
                            'target' => './data/upload',
                            'useUploadName' => true,
                            'useUploadExtension' => true,
                            'overwrite' => true,
                            'randomize' => false
                        ]
                    ]
                ]
            ]); 

Solution

  • You should take a look at the ValidatorChain's.

        // Creating a re-usable chain
        $chain = new ValidatorChain();
        $chain->attachByName('FileMimeType', [
            'mimeType'  => ['image/jpeg', 'image/png' ]
        ]);
        $chain->attachByName('FileImageSize', [
            'minWidth'  => 128,
            'minHeight' => 128,
            'maxWidth'  => 4096,
            'maxHeight' => 4096
        ]);
        $chain->attachByName('FileRenameUpload', [
            'target' => './data/upload',
            'useUploadName' => true,
            'useUploadExtension' => true,
            'overwrite' => true,
            'randomize' => false
        ]);
    
        $this->get('foto1')->setValidatorChain($chain);
        $this->get('foto2')->setValidatorChain($chain);
        $this->get('foto3')->setValidatorChain($chain);