【问题标题】:How can I ignore case in a RegularExpression?如何忽略正则表达式中的大小写?
【发布时间】:2011-05-09 12:55:23
【问题描述】:

我有一个 asp.net MVC 应用程序。有一个名为 File 的实体,它有一个名为 Name 的属性。

using System.ComponentModel.DataAnnotations;

public class File    {
   ...
   [RegularExpression(@"([^.]+[.](jpg|jpeg|gif|png|wpf|doc|docx|xls|xlsx ..., ErrorMessage = "Invali File Name"]
   public string Name{ get; set; }
   ...
}

有一个用于检查文件扩展名的 RegularExpressionValidator。 有没有一种快速的方法可以告诉它忽略扩展名的大小写,而不必将大写变体显式添加到我的验证表达式中? 我在服务器端和客户端都需要这个 RegularExpressionValidator。 "(?i)" 可以用于服务器端,但这在客户端不起作用

【问题讨论】:

    标签: asp.net-mvc regex data-annotations


    【解决方案1】:

    我能想到的一种方法是编写自定义验证属性:

    public class IgnorecaseRegularExpressionAttribute : RegularExpressionAttribute, IClientValidatable
    {
        public IgnorecaseRegularExpressionAttribute(string pattern): base("(?i)" + pattern)
        { }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            var rule = new ModelClientValidationRule
            {
                ValidationType = "icregex",
                ErrorMessage = ErrorMessage
            };
            // Remove the (?i) that we added in the pattern as this
            // is not necessary for the client validation
            rule.ValidationParameters.Add("pattern", Pattern.Substring(4));
            yield return rule;
        }
    }
    

    然后用它装饰你的模型:

    [IgnorecaseRegularExpression(@"([^.]+[.](jpg|jpeg|gif|png|wpf|doc|docx|xls|xlsx", ErrorMessage = "Invalid File Name"]
    public string Name { get; set; }
    

    最后在客户端写一个适配器:

    <script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
    <script type="text/javascript">
        jQuery.validator.unobtrusive.adapters.add('icregex', [ 'pattern' ], function (options) {
            options.rules['icregex'] = options.params;
            options.messages['icregex'] = options.message;
        });
    
        jQuery.validator.addMethod('icregex', function (value, element, params) {
            var match;
            if (this.optional(element)) {
                return true;
            }
    
            match = new RegExp(params.pattern, 'i').exec(value);
            return (match && (match.index === 0) && (match[0].length === value.length));
        }, '');
    </script>
    
    @using (Html.BeginForm())
    {
        @Html.EditorFor(x => x.Name)
        @Html.ValidationMessageFor(x => x.Name)
        <input type="submit" value="OK" />
    }
    

    当然,您可以将客户端规则外部化到一个单独的 javascript 文件中,这样您就不必到处重复了。

    【讨论】:

    • 你成就了我的一天!谢谢!
    【解决方案2】:

    嗯,你能展示一下客户端验证吗?

    嗯,我认为您可以创建自己的从正则表达式派生的属性,并添加忽略大小写的功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多