Validate fileupload control using JavaScript.

Mohammed Imtiyaz Jun 1, 2014

With FileUpload control you can receive files from your web application users. Often, you don't want to receive all file types, but only specific extensions (e.g. images only) depending of your application requirements. Unfortunately, FileUpload control still have not some filter property like Open and Save File dialogs in .NET Windows Forms to limit file types. Because of that, you need to write some additional code to be sure that user will upload regular file type.

HTML

<input id="fileUploadHTML" type="file" onchange="validateFileUpload(this);" />

Aspx (Server Side Control)

<asp:fileupload id="fileUploadAsp" runat="server" onchange="validateFileUpload(this);" ></asp:fileupload>

FileUpload Control client side validation

<script language="javascript" type ="text/javascript">
    function validateFileUpload(obj) {
        var objFilePath = obj.value;

        // This objFileControlId will store the id of the fileupload control.
        // Note : id is case sensitive.

        var objFileControlId = obj.id;

        //Regular Expression for fileupload control.
        var reg = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))+(.JPEG|.jpeg|.JPG|.jpg|.GIF|.gif|.BMP|.bmp|.PNG|.png)$/;

        if (objFilePath.length > 0) {
            // Checks with the control value.
            if (reg.test(objFilePath)) {;
                alert("Success !");
                return true;
            } else {

                //If the condition is not satisfied then shows error message.
                //To clear the fileupload value if the uploaded file is inappropriate.

                var who = document.getElementsByName(objFileControlId)[0];
                who.value = "";
                var who2 = who.cloneNode(false);
                who2.onchange = who.onchange;
                who.parentNode.replaceChild(who2, who);
                alert("Only JPEG, JPG, GIF, BMP and PNG files are allowed!");
                return false;
            }
        }
    }
</script>