Validator - upload files

Can you please advise me how to define a validator form, where I have the option to attach multiple files and only the mimetype image/jpeg is allowed.

For one file is:

     $validator
        ->allowEmptyFile('image_teaser')
        ->requirePresence('image_teaser', 'create')
        ->uploadedFile('image_teaser', [
            'types' => [
                'image/jpeg',
            ],
     ],".jpg");

Do you need multiple image_teaser files, to create a new record for each one? Or do you have multiple different fields in a single record that you need to upload for all at once (e.g. a teaser image and a banner image and a footer image)? The solution is quite different for those two scenarios.

Also, can you share what this part of your form currently looks like?

The form:

echo $this->Form->control('image_gallery[]', [
    'label' => 'Galery *.jpg',
    'type' => 'file',
    'multiple' => 'multiple',
]);

And the validator should verify that only * .jpg files are selected

So how do I validate a field that contains multiple images?

I would think that each of the images would result in a separate record being created in some other table, and you’d do validation of them on a per-record basis.

I do not save images to the database, only to DISK. However, I need if I select multiple images at once:

<input type="file" name="image_gallery[]" multiple="multiple" id="image-gallery">

so that I can verify that I meet the type of jpg.

You’ll need to make a custom validation function for that, then, though you could perhaps call the underlying code for uploadedFile from your function.

1 Like

Can’t display a message below the field error field, probably because it’s called image_gallery[], please how do I display an error message for a given field?

Validation errors

[
    'page_content' => [
        'image_gallery' => [
           'uploadedFile' => 'Allow: .jpg, .png',
        ], 
    ], 
],

Please don’t you know how to display the error message under the field: image_gallery[]

I still didn’t think about it.
Thank you

Here is the solution:

$this->Form->control('image_gallery', [
    'name' => 'image_gallery[]',
    'label' => 'Galery *.jpg',
    'type' => 'file',
    'multiple' => true,
]);