C# 如何从模型属性中创建具有动态模式的regularExpressionAttribute
我想在模式来自其他属性的地方创建这个属性,而不是像原始RegularExpressionAttribute中那样声明静态C# 如何从模型属性中创建具有动态模式的regularExpressionAttribute,c#,validation,asp.net-mvc-3,attributes,C#,Validation,Asp.net Mvc 3,Attributes,我想在模式来自其他属性的地方创建这个属性,而不是像原始RegularExpressionAttribute中那样声明静态 如果您有任何想法,我们将不胜感激-谢谢行中的某些内容应符合要求: public class City { [DynamicReqularExpressionAttribute(PatternProperty = "RegEx")] public string Zip {get; set;} public string RegEx { get; set;}
如果您有任何想法,我们将不胜感激-谢谢行中的某些内容应符合要求:
public class City
{
[DynamicReqularExpressionAttribute(PatternProperty = "RegEx")]
public string Zip {get; set;}
public string RegEx { get; set;}
}
然后:
型号:
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; }
}
视图:
@模范城市
@使用(Html.BeginForm())
{
@HiddenFor(x=>x.RegEx)
@LabelFor(x=>x.Zip)
@EditorFor(x=>x.Zip)
@Html.ValidationMessageFor(x=>x.Zip)
}
重写将ValidationContext作为参数的Validate方法,使用ValidationContext从相关属性获取正则表达式字符串并应用正则表达式,返回匹配的值。您好,这是一个很好的解决方案,但它在客户端验证中不起作用Philipp@Philipp特罗克斯勒,这很正常。我没有实现它,因为客户端验证不是您问题的一部分。要实现这一点,您可以使该属性实现iclientvalidable
,并注册一个自定义jQuery适配器。这里有一个可能让您走上正确道路的示例:Greate,至少我没有得到EntityValidationException,我现在得到了一些希望:)我得到的是PropertyInfo property=validationContext.ObjectType.GetProperty(PatternProperty);返回null,所以现在异常为“MyExpression”是未知属性。花了2天时间才找到这个,你能帮我吗?谢谢:)
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" />
}