How to validate upload file size and file extension using JavaScript ?
Hi guys,
Here i’m giving you some JavaScript code stuffs for validating upload file’s size and extension.
First, let us see our simple html form.

In this form, there’s a file component with name file, a submit button with value “Upload” and a div element with id ‘valid_msg’.
Please note the following points:
1) Form’s enctype must be ‘multipart/form-data’.
2) Form’s method must be ‘post’.
3) Returns onsubmit event function.
When the form is getting submitted, form’s onsubmit event is called and thus call the validation(this) function.

function validation(thisform)
{
with(thisform)
{
if(validateFileExtension(file, "valid_msg", "pdf/office/image files are only allowed!",
new Array("jpg","pdf","jpeg","gif","png","doc","docx","xls","xlsx","ppt","txt")) == false){
return false;
}
if(validateFileSize(file,1048576, "valid_msg", "Document size should be less than 1MB !")==false){
return false;
}
}
}
The validation function carries a parameter, which is our form’s object. The validation function again calls another two functions with some parameters. In the first function (validateFileExtension), there are four parameters:
First is our file object’s name,
Second is the id of the div component, where the error message will be shown.
Third is custom message shown to the user when he tries to upload a file of different extension which does not include in the following array.
Fourth is an array which contains some file extension, which means only these extension are allowed when uploading a file. You can easily add or remove extensions to and from this array.
In the second function (validateFileSize), there are again four parameters passed:
First is, as I already said above, the file component’s name.
Second is maximum size of the uploading file; here it given in bytes;
1048576 byte = 1 MB.
Third is the id of the div component, where the error message will be shown.
Fourth is the custom message.
The above two methods are given below.


The above two functions do the rest. All the major browsers support this. I hope all of you come at the strong part of JavaScript through this post.
Thanks.
- Posted in: DHTML ♦ Javascript
- Tagged: dhtml, file, file extension, file size, file upload, html, javascript, post method

gr8 work
Thank u
Thank you guy !
The code in txt:
function validateFileExtension(component, msg_id, msg, extns)
{
var flag=0;
with(component)
{
var ext=value.substring(value.lastIndexOf(‘.’) + 1);
for (i=0;i maxSize)
{
document.getElementById(msg_id).innerHTML = msg;
component.value = “”;
component.style.backgroundColor = “#eab1b1″;
component.style.border = “thin solid #000000″;
component.focus();
return false;
}
else
{
return true;
}
} // validateFileSize
Good post, thnx
Good