验证属性

验证属性用于在类或类成员上以声明方式强制执行各种验证规则。所有验证属性都派生自 ValidationAttribute 基类。

示例:RequiredAttribute

通过 ValidationAttribute.Validate 方法验证时,如果 Name 属性为 null 或仅包含空格,则此属性将返回错误。

public class ContactModel
{
    [Required(ErrorMessage = "Please provide a name.")]
    public string Name { get; set; }
}

示例:StringLengthAttribute

StringLengthAttribute 验证字符串是否小于字符串的最大长度。它可以选择指定最小长度。两个值都包含在内。

public class ContactModel
{
    [StringLength(20, MinimumLength = 5, ErrorMessage = "A name must be between five and twenty characters.")]
    public string Name { get; set; }
}

示例:RangeAttribute

RangeAttribute 给出数字字段的最大值和最小值。

public class Model
{
    [Range(0.01, 100.00,ErrorMessage = "Price must be between 0.01 and 100.00")]
    public decimal Price { get; set; }
}

示例:CustomValidationAttribute

CustomValidationAttribute 类允许调用自定义 static 方法进行验证。自定义方法必须是 static ValidationResult [MethodName] (object input)

public class Model
{
    [CustomValidation(typeof(MyCustomValidation), "IsNotAnApple")]
    public string FavoriteFruit { get; set; }
}

方法声明:

public static class MyCustomValidation
{
    public static ValidationResult IsNotAnApple(object input)
    {
        var result = ValidationResult.Success;

        if (input?.ToString()?.ToUpperInvariant() == "APPLE")
        {
            result = new ValidationResult("Apples are not allowed.");
        }

        return result;
    }
}