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