如何使用动态模式创建regularExpressionAttribute来自模型属性

问题描述

||
public class City
{
   [DynamicReqularExpressionAttribute(PatternProperty = \"RegEx\")]
   public string Zip {get; set;}
   public string RegEx { get; set;} 
}
我想在模式来自其他属性的地方创建此属性,而不是像原始的RegularExpressionAttribute一样声明静态属性。 任何想法将不胜感激-谢谢     

解决方法

行中的某些内容应该适合该法案:
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\" />
}
    ,重写将ValidationContext作为参数的Validate方法,使用ValidationContext从相关属性中获取正则表达式字符串,然后应用正则表达式,返回匹配的值。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...