Validate asp.net FileUpload control using JavaScript.

  • Share/Save/Bookmark

This article explains about file upload control validation in JavaScript. By default when the user selects invalid format using the file upload control, the server control will not clear the content automatically. using the below code we can check the file extension and if it is not valid file extension then the textbox is cleared. This happens on the client side only using JavaScript.

First lets put a FileUpload control in your aspx page and then call our validation function on client click. Here is the html FileUpload control code.

<asp:fileupload id="FileUpload1" runat="server" />
<input id="btnUpload" onclick="checkFileExtensionLogo('FileUpload1')" type="button" value="Upload" />

when user clicked on the above button we are calling our client side function which validate the extension of the file as well as clears the content.

function checkFileExtensionLogo(Obj)
{
    var elm=document.getElementById(Obj);
    var filePath = elm.value;
    if(filePath.indexOf('.') == -1)
    return false; 

    var validExtensions = new Array();
    var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase(); 

    validExtensions[0] = 'jpg'; 

    for(var i = 0; i < validExtensions.length; i++) {
    if(ext == validExtensions[i]) 

    return true;
    }
    alert('Invalid file, only JPG files are allowed.');
    /* start: The below code clears the content in the file upload control.*/
    var who =elm;
    who.value="";var who2= who.cloneNode(false);
    who2.onchange= who.onchange;
    who.parentNode.replaceChild(who2,who);
    /* End */
    return false;
}

The last few lines of code is the core part of this logic, it clears the content in the file upload control.

Categories : Javascript

Leave a Reply

About Techieon

Techieon is all about sharing Development experience of experienced talented developers of different technologies working in real time. Here at Techieon we talk about latest updates of different technologies, provide solutions to the developers problems, write tutorials on frequently used tools of development and provide tips to developers day to day activities.

This is a Widget Section

This section is widgetized. If you would like to add content to this section, you may do so by using the Widgets panel from within your WordPress Admin Dashboard. This Widget Section is called "Feature Bottom Middle"

Want to Write for Techieon?

Techieon have few opening positions for talented developers who want to share their development experience with Techieon users.If you are interested in writing at Techieon please Contact us or e-mail me for more information.