How to Validate File Size while Uploading using JavaScript or jQuery

It’s always a good idea to add client-side validation before uploading file to the server. The client-side validation adds a great user experience to the file upload section. The file size validation can be added to the file upload field using JavaScript and jQuery. In this example code snippet, we will show you how to validate file size while uploading file using jQuery or JavaScript.

File size validation with JavaScript

The following code shows how to validate file size while uploading using JavaScript.

HTML File Input Element:

<input type="file" id="file" onchange="return fileValidation()"/>

JavaScript Code:

<script>
function fileValidation(){
    var fileInput = document.getElementById('file');
    var fileSize = (fileInput.files[0].size / 1024 / 1024).toFixed(2);
    if(fileSize > 5){
        alert("File size must be less than 5 MB.");
        fileInput.value = '';
        return false;
    }
}
</script>

File Size Validation with jQuery

The following code shows how to validate file size while uploading using jQuery.

HTML File Input Element:

<input type="file" id="file" />

jQuery Library:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.0/jquery.min.js"></script>

jQuery Code:

<script>
$("#file").change(function() {
    var file = this.files[0];
    var fileSize = (file.size / 1024 / 1024).toFixed(2);
    if(fileSize > 5){
        alert("File size must be less than 5 MB.");
        $("#file").val('');
        return false;
    }
});
</script>

Leave a reply

keyboard_double_arrow_up