Validate the size of input=file in HTML5?


You can try to run the following code to validate the size of input type file:

<!DOCTYPE html>
   <html>
      <head>
         <script src="http://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      </head>
      <body>
         <form >
            <input type="file" id="myfile" data-max-size="32154" />
            <input type="submit"/>
         </form>
         <script>
            $(function(){
               $('form').submit(function(){
                  var val = true;
   
                  $('input[type=file][data-max-size]').each(function(){
                  if(typeof this.files[0] !== 'undefined'){
                     var max = parseInt($(this).attr('max-size'),10),
                     mySize = this.files[0].size;
                     val = max > mySize;
                     return val;
                  }
               });
               return val;
            });
         });
      </script>
   </body>
</html>

Updated on: 29-Jan-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements