如何为多个属性重复使用多个数据注释

How to re-use multiple data annotations for multiple properties

我想使用以下数据标注:

[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