1

I'm new to Magento 2.3, i want to validate file upload field.

  • Allowed file formats: jpeg.

I put a method in lib\web\mage\validation.js

require([
        'jquery',
        'jquery/ui',
        'jquery/validate',
        'mage/translate'
    ], function ($) {
    //Validate Image Extensions

    $.validator.addMethod(
            'validate-fileextensions', function (v, elm) {

                var extensions = ['jpeg'];
                if (!v) {
                    return true;
                }
                with (elm) {
                    var ext = value.substring(value.lastIndexOf('.') + 1);
                    for (i = 0; i < extensions.length; i++) {
                        if (ext == extensions[i]) {
                            return true;
                        }
                    }
                }
                return false;
            }, $.mage.__('Disallowed file type.'));
});

and add this class validate-fileextensions in file > input, in this file app\code\{vendor_name}\{module_name}\Block\Adminhtml\Form\Edit\Tab\Main.php

        $fieldset->addField(
            'filename',
            'image',
            [
                'label' => __('File'),
                'title' => __('File'),
                'name' => 'filename',
                'required' => true,
                'disabled' => $isElementDisabled,
                'class' => 'validate-fileextensions'
            ]
        );

but its not working for me, also when i inspect on file > input, i can't see my custom class their. see below image. enter image description here

9
  • do you want to put validation into your custom controll from admin configuration? May 7 '19 at 10:19
  • please don't mind I'm very new to magento, i have a form in adminpanel, in that form their is a file type field, i just want to validate its extention. @DhirenVasoya May 7 '19 at 10:27
  • only validate .jpeg formats images?? May 9 '19 at 9:50
  • Brother @RkRathod, Actually all these ['jpg','jpeg','gif','png','csv','xlsx'] May 9 '19 at 10:00
  • @Dhiren Vasoya Answer is correct any issue of that code May 9 '19 at 10:04
0

You can put the validation into your controller, which save the value of this field like this.

public function __construct(
    ...
    \Magento\Framework\File\UploaderFactory $uploaderFactory,
    ...
) {
    ......
    $this->uploaderFactory = $uploaderFactory;
    .....
}

public function execute()
{
    try {
            $destinationFolder = 'PATH OF FOLDER WHERE YOU NEED TO UPLOAD FILE';
            $yourInputFileName = 'YOURFILEUPLOADFIELDNAME';

            $uploader = $this->uploaderFactory->create(array('fileId' => $yourInputFileName));

            $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']);
            $uploader->setAllowRenameFiles(true);
            $uploader->setFilesDispersion(true);
            $uploader->setAllowCreateFolders(true);
            $result = $uploader->save($destinationFolder);
            return $result['file'];

    } catch (\Exception $e) {             
            throw new FrameworkException($e->getMessage());
    }
}

NOTE $uploader->setAllowedExtensions(['jpg', 'jpeg', 'gif', 'png']); in this line you can specify which file type you need to allowed.

9
  • i have app\code\{vendor_name}\{module_name}\Controller\Adminhtml\Form\Index\Save.php, should i put this code in that file ... ? @Dhiren Vasoya May 7 '19 at 10:47
  • Yes, you can validate file there and show error message according to that. May 7 '19 at 10:49
  • Ok let me try :) May 7 '19 at 10:50
  • I already write the comment that, this is the path of folder where you upload the files into magento. May 7 '19 at 11:01
  • After adding this line \Magento\Framework\File\UploaderFactory $uploaderFactory, i get an error something like this... 1 exception(s): Exception #0 (Magento\Framework\Exception\RuntimeException): Type Error occurred when creating object: EC\Customimport\Controller\Adminhtml\Index\Save\Interceptor etc... @Dhiren Vasoya May 7 '19 at 11:23
0

Reference Link :-

Try This :-

$fieldset->addField(
            'filename',
            'file',
            [
                'label' => __('File'),
                'title' => __('File'),
                'name' => 'filename',
                'required' => true,
                'disabled' => $isElementDisabled
            ]
        );
15
  • Bro with you code user can still upload other extention file... @RkRathod May 9 '19 at 12:41
  • which extension file upload??? May 9 '19 at 12:42
  • your code let me upload all file extenton, when i click on all file when file manager opens.... May 9 '19 at 12:44
  • try this code.. May 9 '19 at 12:49
  • yeah exactly, before raising this question, i applied file tag instead of image image but my senior told me to keep image tag, coz it has a preview feature and checkbox delete feature... In Magento core elements, their is a Image.php file which belongs to this image tag, and it has a built-in class, i think input-file... I also saw many answers for applying custom class in Image tag but they all were very old question so i couldn't understand it... @RkRathod May 10 '19 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.