问题与RegularEx pressionValidator一个ASP.NET FileUpload控件验证文件类型 [英] Problem validating filetypes in an ASP.NET FileUpload control with RegularExpressionValidator

查看:134
本文介绍了问题与RegularEx pressionValidator一个ASP.NET FileUpload控件验证文件类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

code:

<span>Upload Adobe Acrobat file<img src="../../Images/UI/pdf.jpg" style="height: 25;
    width: 20" height="25" width="20" /></span>
<asp:FileUpload ID="uplPdf" runat="server" />
<asp:RegularExpressionValidator ID="valPdf" runat="server" ErrorMessage="Only PDF files are allowed!"
    ValidationExpression="^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.pdf)$" Display="Dynamic"
    ControlToValidate="uplPdf" ValidationGroup="upload" />
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload files" OnClick="btnUpload_Click"
    ValidationGroup="upload" />

背后code:

if (valPdf.IsValid && uplPdf.HasFile)

IsValid的一个有效的PDF文件名后照耀返回false。
需要注意的是,如果不指定文件,返回true。

IsValid returns false after a valid pdf file name was enterd. Note that if no file is specified, returns true.

推荐答案

我在项目设置中添加的文件列表,一个字符串集合。

I added the file list to a string collection in the project settings.

然后我设定的正则表达式编程方式:

Then I set the regex programmatically:

public static string PrepareValidExtensionRegex(string[] allowedFileTypes)
{
    for (int i = 0; i < allowedFileTypes.Length; i++)
    {
        char[] chars = allowedFileTypes[i].ToCharArray();
        int length = chars.Length;
        string[] ret = new string[length];
        for (int j = 0; j < length; j++)
        {
            char ch = chars[j];
            char replacement = char.IsLower(ch)?
                               char.ToUpper(ch): 
                               char.ToLower(ch);
            ret[j] = "[" + ch + replacement + ']';
        }
        allowedFileTypes[i] = '(' + string.Join("", ret) + ')';
    }

    return @"^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(" + 
        string.Join("|", allowedFileTypes) + ")$";
}

//Usage:
string[] allowedFiles = new string[] { "jpg", "gif" };
RegexValidator.ValidationExpression = PrepareValidationExpression(allowedFiles);

这篇关于问题与RegularEx pressionValidator一个ASP.NET FileUpload控件验证文件类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆