Monday, August 16, 2010

How to validate file type with FileUpload control in asp.net using RegularExpression validator

Please note when you check a file type, remember to check of all the combination of letters. Example .Pdf, PDF, pdf, pdF, etc.
Example: Validate any pdf file
<%@ Page Language="C#" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script runat="server"> 
        protected void Save(object sender, EventArgs e)
        {
            this.Page.Validate();
            if (this.IsValid)
            {
                if (this.fuPdfFile.HasFile && 
                    this.fuPdfFile.PostedFile.ContentType.ToLower().Equals("application/pdf"))
                {
 
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:FileUpload runat="server" ID="fuPdfFile" />
            <asp:RegularExpressionValidator 
                runat="server"
                ID="rvafuPdfFile" 
                ControlToValidate="fuPdfFile" 
                ErrorMessage="Invalid File" 
                ValidationExpression="^.*\.([p|P][d|D][f|F])$" />
        </div>
        <asp:Button runat="server" ID="btnSave" OnClick="Save" Text="Save" />
    </form>
</body>
</html>
 
 

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...