File Size Validation using jQuery

by Vincy. Last modified on July 12th, 2022.

In this tutorial, we are going to see “form” file input validation using jQuery. In the previous tutorial, we do this validation using PHP to check if the file input is empty or not.

In this jQuery example, we are validating file size before submitting it for upload. If the file size exceeds 2 MB then the jQuery function will return false.

View DemoDownload

File Upload Form

This code shows HTML form containing file input field. On submitting this form, we are calling jQuery function to validate the size of the uploaded file.

jQuery File Size Validation

<form name="frmFile" id="frmFile" method="post" action=""  onSubmit="return validate();">
	<div><input type="file" name="file" id="file" class="demoInputBox" /> <span id="file_error"></span></div>
	<div><input type="submit" id="btnSubmit" value="Upload"/></div>
</form>

jQuery File Size Validation

This jQuery script checks whether the uploaded file exceeds the size of 2MB. If the file is greater than 2MB then this script will return false.

function validate() {
	$("#file_error").html("");
	$(".demoInputBox").css("border-color","#F0F0F0");
	var file_size = $('#file')[0].files[0].size;
	if(file_size>2097152) {
		$("#file_error").html("File size is greater than 2MB");
		$(".demoInputBox").css("border-color","#FF0000");
		return false;
	} 
	return true;
}

View DemoDownload

↑ Back to Top

Share this page