Client side validation on File upload control using JavaScript : For the file type

The following article shows that how to validate the type of the file that is selected to upload by the user. File Upload on the web page We have a fileupload control on web page page with the id = “fileuploadimages”. We have to validate that the selected file must be bmp, gif, png or jpg.

See the html code of the file upload control below.

<asp:FileUpload ID="fileuploadimages" runat="server" 
         Width="200px"  onChange ="OnUpload();" />

To validate a file extension in JavaScript before uploading a file can be performed by using the onChange event. In this code I am extracting the extension of the selected file and than matching that extension in the array of the valid extensions.
In this code we validates the these file types: bmp, gif, png, jpg and jpeg.

var validFiles = ["bmp", "gif", "png", "jpg", "jpeg"];
function OnUpload() {
    var obj = document.getElementById("<%=fileuploadimages.ClientID%>");
    var source = obj.value;
    var ext = source.substring(source.lastIndexOf(".") + 1, source.length).toLowerCase();
    for (var i = 0; i < validFiles.length; i++) {
                if (validFiles[i] == ext)
    if (i >= validFiles.length) {
        alert("THAT IS NOT A VALID IMAGE\nPlease load an image with an " & 
          "extention of one of the following:\n\n" + validFiles.join(", "));
        document.getElementById("<%=fileuploadimages.ClientID%>").value = '';
     return true;

The upload file will be stop if the there is blank file name.