的东西应该符合该法案:
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" />
}
嗨达林 很好的解决方案,但它不会在客户端验证unobtrustiv 菲利普 – 2011-05-26 13:10:35
@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
谢谢...现在它的工作原理 – 2011-05-26 21:22:38