The following script will add these validations:
- Limit the number of uploaded files to max 5
- Limit the total number of uploaded files to 10MB
- 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!