IValidatableObject
用於對單個模型執行多重驗證。在你的情況下,你有一個User
模型,你想要做三個驗證,你可以通過在User
模型中實現IValidatableObject
來完成。
ValidationContext
沒有帶來太多好處(除了提供對上下文的訪問),因爲我們可以直接在Validate
方法中訪問所有屬性。
通過IValidatableObject
執行與單個模型相關的多個驗證的示例。 (那麼ValidationContext
在這裏有什麼用處?)
public class Party : IValidatableObject
{
[Required(ErrorMessage = "Start date is required")]
[FutureDateValidator(ErrorMessage = "Start date should be a future date")]
public DateTime StartDate { get; set; }
[Required(ErrorMessage = "Duration is required")]
public int DurationInHours { get; set; }
[Required(ErrorMessage = "No. of joinees is required")]
[Range(2, 10, ErrorMessage = "No. of joinees should be minimum 2 and not more than 10")]
public int NoOfJoinees { get; set; }
public bool Drinks { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (StartDate.TimeOfDay > new TimeSpan(22 - DurationInHours, 0, 0))
{
yield return new ValidationResult("The party should not exceed after 10.00 PM");
}
if (NoOfJoinees < 5 && Drinks)
{
yield return new ValidationResult("Drinks are only allowed if no. of joinees is 5 or more.");
}
}
}
我不明白你爲什麼要使用ValidationContext? – VJAI
我真的問是否可以用它。但是,如果這是不好的做法或真的不打算用於確定「驗證組」,那麼請讓我知道。 – mhapps