4

I'm going to upload one image. I need to put below validations on Client side & Server Side

  • Allowed file formats: jpeg, jpg, png
  • Max. File Size is 5MB.
  • Image size should be 100 Width x 100 height

lib\web\mage\validation.js

From above file, not able to achieve this.

app\code\Custom\Module\Block\MyPost\Edit.php

<input type="file" name="image" id="image" value=""  data-validate="{required:true}" />

2 Answers 2

8

We should create new validation classes: validate-filesize, validate-fileextensions & validate-image-height-width.

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

    $.validator.addMethod(
            'validate-filesize', function (v, elm) {
                var maxSize = 5 * 102400;
                if (navigator.appName == "Microsoft Internet Explorer") {
                    if (elm.value) {
                        var oas = new ActiveXObject("Scripting.FileSystemObject");
                        var e = oas.getFile(elm.value);
                        var size = e.size;
                    }
                } else {
                    if (elm.files[0] != undefined) {
                        size = elm.files[0].size;
                    }
                }
                if (size != undefined && size > maxSize) {
                    return false;
                }
                return true;
            }, $.mage.__('The file size should not exceed 5MB'));

    //Validate Image Extensions

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

                var extensions = ['jpeg', 'jpg', 'png', 'gif'];
                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.'));

    //Validate Image Width and Height

    $.validator.addMethod(
            'validate-image-height-width', function (v, elm) {

                if (!v) {
                    return true;
                }
                with (elm) {
                    var file, img;
                    if ((file = elm.files[0])) {
                        img = new Image();
                        img.onload = function () {
                            var height = this.height,
                                    width = this.width;
                            if (height > 100 || width > 100) {
                                return false;
                            }

                            return true;
                        };
                    }
                }
                return false;
            }, $.mage.__('Height and Width must not exceed 100px.'));
});

I followed a guide to create the script above: https://gist.github.com/obukhow/5040981

4
  • Thanks @Khoa. For Image Height & Width Validation?
    – Jackson
    Sep 2, 2016 at 7:16
  • I updated the new case, however, not yet test. If there is any error, let's me know. Sep 2, 2016 at 7:46
  • 1
    @khoa where I have to add this above code. Please specify the location as well.
    – sudo55
    Dec 19, 2018 at 22:17
  • Thanks, @KhoaTruongDinh it's a great solution.
    – AboElnouR
    Aug 31, 2021 at 8:28
0

The following script will add these validations:

  1. Limit the number of uploaded files to max 5
  2. Limit the total number of uploaded files to 10MB
  3. Allowing only PNG, JPG or JPEG files
  • Create a file called rule.js in:

app/code/Vendor/FancyModule/view/frontend/web/js/validation/rules.js with the following content:

define([
    'jquery',
    'jquery/validate',
    'mage/translate'
], function($) {
    'use strict';

    return function() {
        $.validator.addMethod(
            'validatefileupload',
            function(value, element) {
                var files = element.files;
                var allowedExtensions = ['png', 'jpg', 'jpeg'];
                var maxSize = 10 * 1024 * 1024;
                var totalSize = 0;
                if (files.length > 5) {
                    return false;
                }
                for (var i = 0; i < files.length; i++) {
                    var file = files[i];
                    var fileName = file.name;
                    var fileExtension = fileName.split('.').pop().toLowerCase();
                    var fileSize = file.size;
                    totalSize += fileSize;

                    if (!allowedExtensions.includes(fileExtension)) {
                        return false;
                    }
                }

                // Check if total size exceeds the limit
                if (totalSize > maxSize) {
                    return false;
                }

                return true;
            },
            $.mage.__('Please upload up to 5 images with PNG, JPG, or JPEG format and ensure the total file size is not more than 10MB.')
        );
    }
});
  • Make sure you have the requirejs-config.js file in the:

app/code/Vendor/FancyModule/view/frontend/requirejs-config.js with this content:

var config = {
    config: {
        mixins: {
            'mage/validation': {
                'Vendor_FancyModule/js/validation/rules': true
            }
        }
    }
}
  • add the rule to your input of type file

    <input type="file" name="file[]" id="imageInput" multiple data-validate="{required:true,'validatefileupload':true}">

Hope this post will help someone!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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