gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:30:13 27 4
gpt4 key购买 nike

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; }
}

Controller :

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" />
}

关于c# - 如何使用来自模型属性的动态模式创建 regularExpressionAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6137719/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com