上次我们扩展了一个属性的验证特性。这次我们直接验证整个实体类。只要直接继承IValidatableObject这个接口,然后实现接口成员就可以了。
看代码
public class Review : IValidatableObject { public int Id { get; set; } [Range(1, 10)] [Required] [Display(Name = "评分")] public int Rating { get; set; } [Display(Name = "内容")] [MinLength(15)] public string Body { get; set; } [Required] [Display(Name = "评论者")] public string ReviewerName { get; set; } [IsCellPhone(ErrorMessage = "{0} 丫的格式根本不正确")] [Display(Name = "手机号码")] public string CellPhone { get; set; } public int ArticleId { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (Rating < 3 && ReviewerName.Equals("大宝")) { yield return new ValidationResult("哼,大宝,你评的分太低啦,你不能这样做!"); } } }
验证结果: