如何解决如何为多个属性重用多个数据注释
我想使用以下数据注释:
[RegularExpression(@"^\d+\.\d{0,2}$",ErrorMessage = "Invalid price entered,please re-check the price and try again.")]
[Range(0,999999.99,ErrorMessage = "The price must be less than £999999.99")]
对于我的类中的所有价格属性,但我不想重用注释并希望将它们组合成例如 [PriceValidation] 并将其打印在所有属性上方。 这能做到吗? TIA
解决方法
您可以创建自己的 custom validation attribute 来封装所需的逻辑。对于初学者来说是这样的:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter)]
public class PriceValidationAttribute : ValidationAttribute
{
private static readonly Regex Regex = new Regex(@"^\d+\.\d{0,2}$",RegexOptions.Compiled);
protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
var stringValue = Convert.ToString(value,CultureInfo.CurrentCulture);
if (stringValue != null && !Regex.IsMatch(stringValue))
{
return new ValidationResult("Invalid price entered,please re-check the price and try again.");
}
var doubleValue = Convert.ToDouble(value);
if (doubleValue > 999999.99 || doubleValue < 0)
{
return new ValidationResult("The price must be less than £999999.99");
}
return ValidationResult.Success;
}
}
您也可以考虑使用 fluent validation library。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。