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>

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() {
	var file_size = $('#file')[0].files[0].size;
	if(file_size>2097152) {
		$("#file_error").html("File size is greater than 2MB");
		return false;
	return true;

View DemoDownload

↑ Back to Top

Share this page