File Size Validation using jQuery

by Vincy. Last modified on July 6th, 2023.

In this tutorial, we will see “form” file input validation using jQuery. In the previous tutorial, we do this validation using PHP to check whether the file input is empty.

In this jQuery example, we validate file size before submitting it for upload. The jQuery function will return false if the file size exceeds 2 MB.

View Demo

File Upload Form

This code shows an HTML form containing the file input field. On submitting this form, we call the 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

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

↑ Back to Top

Share this page