本文介绍了如何创建regularEx pressionAttribute动态模式,从模型属性来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class City
{
[DynamicReqularExpressionAttribute(PatternProperty = "RegEx")]
public string Zip {get; set;}
public string RegEx { get; set;}
}
我woud要建立这个属性,该模式对于来自其他财产,而不是声明静态像原来RegularEx pressionAttribute。
I woud like to create this attribute where the pattern come from an other property and not declare static like in the original RegularExpressionAttribute.
任何想法,将AP preciated - 谢谢
Any ideas would be appreciated - Thanks
推荐答案
在电线之间的事情应该符合这个要求:
Something among the lines should fit the bill:
public class DynamicReqularExpressionAttribute : 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
{
[DynamicReqularExpression(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" />
}
这篇关于如何创建regularEx pressionAttribute动态模式,从模型属性来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!