How To Validate Max File Size Using Javascript

Websolutionstuff | Aug-03-2020 | Categories : Laravel PHP jQuery

This article will show us how to validate max file size using javascript. Many times we have a requirement to check the validation of the maximum file size before uploading to the server. So, I have created a post on max file upload validation jquery.

So, let's see file upload validation in javascript or file upload size validation using jquery.

I have created one blade file and checked file size using the if condition in jquery.

<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>

 

And you will get output like this.

file upload size validation

 


You might also like:

Recommended Post
Featured Post
How To Generate QRcode In Laravel
How To Generate QRcode In Lara...

In this example, I will give information about how to generate QR code in laravel. As per the current trend, many w...

Read More

Jun-01-2020

How To Add Index In Laravel 10 Migration
How To Add Index In Laravel 10...

In this article, we will see how to add an index in laravel 10 migration. Here, we will learn about the laravel 10...

Read More

May-03-2023

Datatables Show And Hide Columns Dynamically In jQuery
Datatables Show And Hide Colum...

In this article, we will see how to hide and show columns in datatable in jquery. This example shows how you can ma...

Read More

Jun-07-2022

Laravel 11 Install Yajra Datatable Example
Laravel 11 Install Yajra Datat...

In this tutorial, we'll explore an example of installing Yajra Datatable in Laravel 11. In every project, it's e...

Read More

Apr-10-2024