How to validate input type file size in jQuery for multiple records

You can validate input file size in jquery for multiple records by using $.each() method on file input array and validate each file by specifying the max file size limit.

Answers 1
  • Validate input type file size for multiple records in jQuery

    <!-- HTML Input tag -->
    <input type="file" name="file" id="file" multiple />
    <div id="resp"></div>
    
    <!--jQuery CDN with JavaScript Code -->
    <!-- jQuery CDN --> 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
    var fileInput = document.getElementById('file');
    fileInput.addEventListener("change", function(event){
        let files = event.target.files;
        let ResponseTxt = '';
        $(files).each(function(index, file) {
            if(file.size > 1048576){
                ResponseTxt += 'File : '+file.name + ' is greater than 1MB. <br/>';
            }else{
                ResponseTxt += 'File : '+file.name + ' has a valid size. <br/>';
            }
        });
        document.getElementById('resp').innerHTML = "";
        document.getElementById('resp').innerHTML += ResponseTxt;
    });
    </script>
    
    0
  • Back to code snippet queries related jquery