Asp.net-Mvc

如何忽略正則表達式中的大小寫?

  • May 9, 2011

我有一個 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)" 可用於伺服器端,但這在客戶端不起作用

我能想到的一種方法是編寫自定義驗證屬性:

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 文件中,這樣您就不必在任何地方重複它。

引用自:https://stackoverflow.com/questions/5937174