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.
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.
<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>
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;
}