【问题标题】:RegEx for specific extension validation [duplicate]用于特定扩展验证的正则表达式 [重复]
【发布时间】:2019-05-27 12:25:26
【问题描述】:

我正在尝试使用 DataAnnotations 在客户端(剃须刀)上验证上传文件扩展名,但看起来无论我上传什么文件,我总是会收到“错误消息”,

 [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">

【问题讨论】:

  • 如果您不想匹配空格,请不要添加空格。
  • @WiktorStribiżew 我不确定我是否理解。这是我想要验证的唯一扩展,其余的都假设得到错误消息。
  • @"^.*\.(jpg|JPG|gif|docx|doc|DOC|pdf|PDF)$"
  • [RegularExpression(@"^.*\.(jpg |JPG|gif|docx|doc|DOC|pdf|PDF)$",我很难得到错误
  • 你为什么在jpg后面插入一个空格?这是使用我的建议的唯一问题吗?

标签: c# regex asp.net-core-mvc entity-framework-core data-annotations


【解决方案1】:

您的原始表达式工作正常,让我们使用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 可视化正则表达式:

【讨论】:

    猜你喜欢
    • 2018-11-13
    • 2016-11-15
    • 2011-05-16
    • 2016-10-28
    • 2013-11-02
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多