2011-05-26 73 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来从相关的属性,正则表达式串并应用正则表达式,返回匹配的值。