驗證屬性

驗證屬性用於在類或類成員上以宣告方式強制執行各種驗證規則。所有驗證屬性都派生自 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;
    }
}