2011-05-09 121 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並添加函數來忽略大小寫。我能想到的