Extension Validator is not called

Hello everyone!
I’ve been trying to set up a small file upload that accepts only xml files; I picked the Extension-Validator to safeguard my app against users who don’t want to upload this type of files.
Let’s set the frame.


use Laminas\Validator\File\Extension;

class ImportForm extends Form
{
    public function __construct($name = null)
    {
        parent::__construct('foo');

        $inputFilter = new InputFilter();
        $inputFilter->add([
            'name' => 'fileUpload',
            'required' => false,
            'filters' => [],
            'validators' => [
                [
                    'name' => Extension::class,
                    'options' => [
                        'extension' => ['xml']
                    ]
                ]
            ]
        ]);
        
       $this->setInputFilter($inputFilter);

        $this->add([
            'name' => 'fileUpload',
            'type' => 'file',
            'options' => [
                'label' => 'Upload XML'
            ],
            'attributes' => [
                'class' => 'form-control',
                'accept'=> 'application/xml'
            ]
        ]);

// some other field definitions here

And in my controller in the action

$importForm = new ImportForm();
$importForm->setData($request->getPost());
if(!$importForm->isValid())
{
 return ['form' => $form, 'importForm' => $importForm];
}
print_r($request->getFiles()["fileUpload"]);

So, to my understanding, the print_r should not be called when I try to upload a txt-file, and there should an error pop saying that the file extension is wrong.
That does not happen. The print_r is called.

Anyone got some thoughts on this? I am stuck.

Thanks!

Hello makxk,

try this …

$form = $this->serviceItem->getFormFileUpload();
$request = $this->getRequest();
if ($request->isPost()) {
   $post = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
   $form->setData($post);
   if ($form->isValid()) {
       $formData = $form->getData();
        ... $formData['fileupload']['name'] ...
   }
}
1 Like

See also the related documentation: laminas-form: File Uploads – Basic Example – The Controller Action