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:

iPhone Launch Screen Sizes

iPhone Portrait iOS 8 Retina HT 5.5 = 1242 X 2208 Retna HD 4.7 = 750 X 1134 iPhone Landscape iOS 8 Retina HD 5.5  2208 X 1242 iPho...