首页 > 解决方案 > 如何为多个属性重用多个数据注释

问题描述

我想使用以下数据注释:

[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

标签: c#asp.netdata-annotations

解决方案


您可以创建自己的自定义验证属性,该属性将封装所需的逻辑。对于初学者来说是这样的:

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

您也可以考虑使用流利的验证库


推荐阅读