2011-05-26 71 views
6
public class City 
{ 
    [DynamicReqularExpressionAttribute(PatternProperty = "RegEx")] 
    public string Zip {get; set;} 
    public string RegEx { get; set;} 
} 

我woud想創建這個屬性,該模式對於來自其他財產,而不是聲明靜態像原來RegularExpressionAttribute來。如何創建regularExpressionAttribute動態模式從模型屬性

任何想法,將不勝感激 - 感謝在電線之間

回答

6

的東西應該符合該法案:

public class DynamicRegularExpressionAttribute : ValidationAttribute 
{ 
    public string PatternProperty { get; set; } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     PropertyInfo property = validationContext.ObjectType.GetProperty(PatternProperty); 
     if (property == null) 
     { 
      return new ValidationResult(string.Format("{0} is unknown property", PatternProperty)); 
     } 
     var pattern = property.GetValue(validationContext.ObjectInstance, null) as string; 
     if (string.IsNullOrEmpty(pattern)) 
     { 
      return new ValidationResult(string.Format("{0} must be a valid string regex", PatternProperty)); 
     } 

     var str = value as string; 
     if (string.IsNullOrEmpty(str)) 
     { 
      // We consider that an empty string is valid for this property 
      // Decorate with [Required] if this is not the case 
      return null; 
     } 

     var match = Regex.Match(str, pattern); 
     if (!match.Success) 
     { 
      return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName)); 
     } 

     return null; 
    } 
} 

然後:

型號:

public class City 
{ 
    [DynamicRegularExpression(PatternProperty = "RegEx")] 
    public string Zip { get; set; } 
    public string RegEx { get; set; } 
} 

控制器:

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var city = new City 
     { 
      RegEx = "[0-9]{5}" 
     }; 
     return View(city); 
    } 

    [HttpPost] 
    public ActionResult Index(City city) 
    { 
     return View(city); 
    } 
} 

查看:

@model City 
@using (Html.BeginForm()) 
{ 
    @Html.HiddenFor(x => x.RegEx) 

    @Html.LabelFor(x => x.Zip) 
    @Html.EditorFor(x => x.Zip) 
    @Html.ValidationMessageFor(x => x.Zip) 

    <input type="submit" value="OK" /> 
} 
+0

嗨達林 很好的解決方案,但它不會在客戶端驗證unobtrustiv 菲利普 – 2011-05-26 13:10:35

+1

@Philipp特克斯勒工作,這是正常的。我沒有實現它,因爲客戶端驗證不是你問題的一部分。爲了達到這個目的,你可以使這個屬性實現IClientValidatable並註冊一個自定義的jQuery適配器。下面是一個例子,可能會讓你在正確的軌道上:http://stackoverflow.com/questions/4784943/asp-net-mvc-3-client-side-validation-with-parameters/4784986#4784986 – 2011-05-26 14:10:10

+0

謝謝...現在它的工作原理 – 2011-05-26 21:22:38

0

覆蓋的驗證方法,它採用了ValidationContext作爲參數,使用ValidationContext來從相關的屬性,正則表達式串並應用正則表達式,返回匹配的值。