Pulse7
7/16/2017 - 8:25 AM

IValidatable object validation annotations

IValidatable object validation annotations

public class RestaurantReview:IValidatableObject
    {
        public int ID { get; set; }
        public int RestaurantId { get; set; }
        [Required]
        [StringLength(1024)]
        public string Review { get; set; }
        [Range(1,10)]
        public int Rating { get; set; }
        [MaxWords(1)]
        public string ReviewerName { get; set; }
        [ForeignKey("RestaurantId")]
        public virtual Restaurant Restaurant { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            if (Rating<2 && ReviewerName.ToLower().StartsWith("scott"))
            {
                yield return new ValidationResult("Sorry Scott you can't do this");
            }
        }
    }