用于特定扩展验证的正则表达式

RegEx for specific extension validation

我正在尝试使用 DataAnnotations 在客户端(razor)验证上传文件扩展名,但看起来无论我上传什么文件,我总是得到 "Error Message"、

 [RegularExpression(@"^.*\.(jpg | JPG | gif | docx | doc | DOC | pdf | PDF)$",
           ErrorMessage = "bla bla")]
        public IFormFile MyImage { get; set; }

我的代码如下:

 <input name="MyImage" class="input-validation-error" id="MyImage" aria-invalid="true" aria-describedby="MyImage-error" type="file" data-val="true" data-val-regex-pattern="^.*\.(jpg | JPG | gif | docx | doc | DOC | pdf | PDF)$" data-val-regex="bla bla">

您的原始表达式工作正常,让我们使用 i 标志稍微简化它:

(.*\.)(jpe?g|gif|docx?|pdf)$

DEMO

测试

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"(.*\.)(jpe?g|gif|docx?|pdf)$";
        string input = @"any_file_name_we_wish_here_with_!@#$%^&*_1234567.jpg
any_file_name_we_wish_here_with_!@#$%^&*_1234567.jpeg
any_file_name_we_wish_here_with_!@#$%^&*_1234567.JPG
any_file_name_we_wish_here_with_!@#$%^&*_1234567.docx
any_file_name_we_wish_here_with_!@#$%^&*_1234567.doc
any_file_name_we_wish_here_with_!@#$%^&*_1234567.pdf
any_file_name_we_wish_here_with_!@#$%^&*_1234567.gif
any_file_name_we_wish_here_with_!@#$%^&*_1234567.mp3
any_file_name_we_wish_here_with_!@#$%^&*_1234567.mp4";
        RegexOptions options = RegexOptions.Multiline | RegexOptions.IgnoreCase;

        foreach (Match m in Regex.Matches(input, pattern, options))
        {
            Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
        }
    }
}

正则表达式电路

jex.im 可视化正则表达式: