2011-05-09 123 views
10

我有一个asp.net MVC应用程序。有一个名为File的实体,它有一个名为Name的属性。如何忽略RegularExpression中的大小写?

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)”可以用于服务器端,但这不起作用客户端

回答

8

一种方法是编写自定义验证属性:

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文件,以便您不必在任何地方重复。

+0

非常感谢! – 2013-04-24 08:07:45

+0

你已经度过了我的一天!谢谢! – Pal 2016-11-16 08:47:07

0

你可以显示客户端验证吗?

umh我认为你可以创建你自己的属性,派生自RegularExpression并添加函数来忽略大小写。我能想到的