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”.


<html>
<body>
<form action="uploadAction" method="post" enctype="multipart/form-data" onsubmit="return validation(this)">
<input type="file" name="file"/>
<input type="submit" value="Upload"/>
<div id="valid_msg"/>
</form>
</body>
</html>

Please note the following points:
1) Form’s enctype must be ‘multipart/form-data’.
2) Form’s method must be ‘post’.
3) “returns: statement in onsubmit function.

When the form gets submitted, form’s onsubmit event is called and thus call our validation() 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 said two methods are given below.


function validateFileExtension(component,msg_id,msg,extns)
{
   var flag=0;
   with(component)
   {
      var ext=value.substring(value.lastIndexOf('.')+1);
      for(i=0;i<extns.length;i++)
      {
         if(ext==extns[i])
         {
            flag=0;
            break;
         }
         else
         {
            flag=1;
         }
      }
      if(flag!=0)
      {
         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;
      }
   }
}


function validateFileSize(component,maxSize,msg_id,msg)
{
   if(navigator.appName=="Microsoft Internet Explorer")
   {
      if(component.value)
      {
         var oas=new ActiveXObject("Scripting.FileSystemObject");
         var e=oas.getFile(component.value);
         var size=e.size;
      }
   }
   else
   {
      if(component.files[0]!=undefined)
      {
         size = component.files[0].size;
      }
   }
   if(size!=undefined && size>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;
   }
}

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.

About these ads

23 Comments

  1. Avinash

    gr8 work :)

  2. thelearner

    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

  3. Good post, thnx

  4. Good

  5. Rathod

    Thanks…

  6. abhi

    please place code instead of image.

  7. Daniel

    Hello, Thank you for this tutoriel ! Could you please post the function(ValidateFile Size) code in text so we can copy-paste it ? Thank you so much

  8. Hi all,

    All images are replaced with code.

  9. Wonderfull. I usually work with free hosting where the upload size is limited. That for, if somebody try to upload 5 big images in one time, script works, but upload is not succesfull. Only I need was this image size validation before send to server by PHP. Many, many thanks.

  10. fahim

    nice sir!!!! thanks a lot….fahim

  11. Vani Senthil

    Good post thanks a lot

  12. wow…. this is the best example…. thanks for sharing… ^^

  13. hey this code is not working for me.
    where is uploadaction in your form action.
    can you help me. ?

  14. andrew

    can you add a function to validate file dimensions i’ve been trying but no luck
    function validateFileDimensions(component,dimensiontest,msg_id,msg)
    {
    with(component)
    {

    var width = component.width;

    if(width>dimensiontest)
    {
    document.getElementById(msg_id).innerHTML=msg;
    component.value=””;
    component.style.color=”#000000″
    component.style.backgroundColor=”#ffff00″;
    component.style.border=”thin solid #000000″;
    component.focus();
    return false;
    }
    else
    {
    return true;
    }}
    }

    is this possible????

    • Hi andrew,

      I never tried it out. Anyway let me try.

      • andrew

        Hi again have you had chance to try this out yet, don’t mean to sound pushy, what you’ve done is great and works fine, and thanks for that. but, it is really frustrating I’ve tried everything i can think of to get it working and i just can’t do it, not knowing why is really annoying me.

  15. Serdar

    how use script input file change event?

    • Hi Serdar,

      Actually what do you mean by input file change? Could you please explain?

  16. Florin

    Hi,
    The script is great but if te input file is not mandatory and you don’t want to upload anything the error message appears anyway.

    Thanks!

    • Florin

      I found the solution for my question:

      function validation(thisform){
      if(document.getElementById(“file”).value != “”) {
      with(thisform){
      ……………………
      ……………………
      ……………
      }
      }
      }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 431 other followers

%d bloggers like this: