How to validate upload file size and file extension using JavaScript?

Today, We want to share with you file upload size limit validation in javascript.In this post we will show you file upload validation in javascript, hear for Validation of file size while uploading using JavaScript / jQuery we will give you demo and example for implement.In this post, we will learn about input type file size limit javascript with an example.

How to validate upload file size and file extension using JavaScript ?

index.html

<div style="margin:0 auto; width:70%; text-align:center">
<form id="form">
<input type='file' id="file" />
<br />
<span style="color:red"> Note: Please select only image file (eg: .png, .jpeg, .jpg, .gif etc)<br /> Max File size : 1MB allowed </span><br />
<img id="img" src="https://placehold.it/200x200" alt="No image uploaded" />
</form>
<br />

$(function() {
$("#file").change(function () {
	    if(fileExtValidate(this)) {
	    	 if(fileSizeValidate(this)) {
	    	 	showImg(this);
	    	 }	 
	    }    
    });

// File extension validation, Add more extension you want to allow
var validExt = ".png, .gif, .jpeg, .jpg";
function fileExtValidate(fdata) {
 var filePath = fdata.value;
 var getFileExt = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();
 var pos = validExt.indexOf(getFileExt);
 if(pos < 0) {
 	alert("This file is not allowed, please upload valid file.");
 	return false;
  } else {
  	return true;
  }
}

// file size validation
// size in kb
var maxSize = '1024';
function fileSizeValidate(fdata) {
	 if (fdata.files && fdata.files[0]) {
                var fsize = fdata.files[0].size/1024;
                if(fsize > maxSize) {
                	 alert('Maximum file size exceed, This file size is: ' + fsize + "KB");
                	 return false;
                } else {
                	return true;
                }
     }
 }

 // display img preview before upload.
function showImg(fdata) {
        if (fdata.files && fdata.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#img').attr('src', e.target.result);
            }

            reader.readAsDataURL(fdata.files[0]);
        }
    }

	
});
</script>

Get File Size using JavaScript

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Get File Size Before Uploading in JavaScript - www.pakainfo.com</title>
</head>

<body>
    <p>
        <input type="file" id="file" multiple onchange="GetFileSize()" />
    </p>
    
    <p id="fp"></p>
</body>

<script>
    function GetFileSize() {
        var fi = document.getElementById('file'); // GET THE FILE INPUT.

        // VALIDATE OR CHECK IF ANY FILE IS SELECTED.
        if (fi.files.length > 0) {
            // RUN A LOOP TO CHECK EACH SELECTED FILE.
            for (var i = 0; i <= fi.files.length - 1; i++) {

                var fsize = fi.files.item(i).size;      // THE SIZE OF THE FILE.
                document.getElementById('fp').innerHTML =
                    document.getElementById('fp').innerHTML + '<br /> ' +
                        '<b>' + Math.round((fsize / 1024)) + '</b> KB';
            }
        }
    }
</script>
</html>

Get File Size using jQuery

index.html

<head>
    <title>Get File Size using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>

<body>
    <p>
        <input type="file" id="file" multiple />
    </p>
    
    <p id="fp"></p>
</body>

<script>
    $(document).ready(function () {
        $('#file').change(function () {
            if (this.files.length > 0) {

                $.each(this.files, function (index, value) {
                    $('#fp').html($('#fp').html() + '<br />' +
                        '<b>' + Math.round((value.size / 1024)) + '</b> KB');
                })
            }
        });
    });
</html>

File upload size validation using jQuery with demo

index.html

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#accountDP").change(function(){
$("#display_err").html("");
$(".profile_dp_store").css("border-color","#F0F0F0");
var file_size = $('#accountDP')[0].files[0].size;
if(file_size>500000) {
$("#display_err").html("<p style='color:#FF0000'>File size is greater than 500kb</p>");
$(".profile_dp_store").css("border-color","#FF0000");
return false;
} 
return true;
});
});
</script>
</head>
<body>
<span id="display_err"></span>
<input type="file" id="accountDP" name="profile_dp_store" class="profile_dp_store">
</body>
</html>

I hope you get an idea about File upload size validation using jQuery with demo.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.