DEV Community

loading...

How To Validate Max File Size Using JavaScript

websolutionstuff profile image Websolutionstuff Originally published at websolutionstuff.com ・2 min read

Hello Friends,

In this post I will help you to validate max file size using javascript, Many time we have requirement to check validation of maximum size of file before uploading in server. So I have created post how to validate max file size using javascript.

It's very simple to implement get max file size using javascript or jquery.

I have created one blade file and check file size using if condition in jquery. in javascript i will check on file on change event and get file using on change event.

After that i will get size of file and then check condition if file size max or not then display message according file size. if file size is max then display "File upload size is larger than 2MB" else nothing to display.

<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>File upload size validation in javascript - websolutionstuff.com</title>
  <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>  
</head>
<body>
  <h3 style="text-align: center;">File upload size validation in javascript - websolutionstuff.com</h3>
  <div class="col-md-6 col-md-offset-5"><br>
  <input type="file" name="file"  id="filesizecheck"><br>
  <span id="error-message" class="validation-error-label"></span>
  </div>
</body>
</html>
<script type="text/javascript">
  $(document).ready(function(){
    $('#filesizecheck').on('change',function(){
      for(var i=0; i< $(this).get(0).files.length; ++i){
        var file1 = $(this).get(0).files[i].size;
        if(file1){
          var file_size = $(this).get(0).files[i].size;
          if(file_size > 2000000){
            $('#error-message').html("File upload size is larger than 2MB");
            $('#error-message').css("display","block");
            $('#error-message').css("color","red");
          }else{
            $('#error-message').css("display","none");
          }
        }
      }
    });
  });
</script>
Enter fullscreen mode Exit fullscreen mode

And you will get output like this.

Validate Max File Size

Read Also : How To Delete Multiple Records Using Checkbox In Laravel

Discussion (0)

pic
Editor guide