Multiple selected files size validation before form submit in jQuery.
HTML Form
1 2 3 4 5 | <form action="#" method="post" enctype="multipart/form-data"> <input type="file" name="invoice[]" id="customFile" required multiple> <label for="customFile">Choose file</label> <button class="btn btn-success" type="submit" style="margin-left: 15px;">Upload</button> </form> |
jQuery Validation
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("form").submit(function(){ //==Check File Size==> var splashArray = new Array(); var files = $('form :input[type=file]').get(0).files; for (i = 0; i < files.length; i++) { splashArray.push(files[i].size); } //alert(JSON.stringify(splashArray)); var total = 0; for (var i = 0; i < splashArray.length; i++) { total += splashArray[i] << 0; } //alert(total); if (total > 5000000){ alert('Total File size should not more than 5 MB'); return false; } }); }); </script> |