Validate file Extension in ASP.net using JavaScript


I had seen many post in forums people asking how to make sure only image files or only .doc file or .xls file should be uploaded or selected.

Below is a simple JavaScript function which make sure that only the extension specified is valid during upload/selection process.

Here I am using Custom validator to call the function. You can use this JavaScript directly on click of a button or FileUpload control.


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>

    <script type="text/javascript">
    function ValidateFile(Source, args)
    {
        var FileUploadCtrl = document.getElementById('FileUpload1');
        var FilePath = FileUploadCtrl.value;
    //
        var Extension = FilePath.substring(FilePath.lastIndexOf('.') + 1).toLowerCase();
        if (Extension == "jpg" || Extension == "gif" || Extension == "png")
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
    }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select a valid doc or jpeg file"
            ControlToValidate="FileUpload1" ClientValidationFunction="ValidateExcelFile"></asp:CustomValidator>
        <br />
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
    </form>
</body>
</html>

No Comments