LSTANCZYK
9/25/2017 - 1:34 AM

gistfile1.txt

  public class MaxWords : ValidationAttribute
    {
        private int _maxWords;

        public MaxWords(int maxWords)
            : base("{0} has too many words")
        {
            _maxWords = maxWords;
        }


        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                var valueAsString = value.ToString();
                if (valueAsString.Split(' ').Length > _maxWords)
                {
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(errorMessage);
                }
            }
            return ValidationResult.Success;
        }
    }
    
    
    
    public class ProductReview:IValidatableObject
    {
        public int Id { get; set; }


        [Range(1,10,ErrorMessage="Between 1 and 10 only")]
        public int Rating { get; set; }
        
        public int ProductId { get; set; }
        
       
        [MaxWords(2)]
        [Display(Name="Reviewer Name")]
        [DisplayFormat(NullDisplayText="Unkown")]
        public string ReviewerName { get; set; }

         [MaxLength(1024)]
        // [Required]
        public string Comments { get; set; }



         public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
         {
             if (Rating < 2 && ReviewerName.ToLower().StartsWith("dee"))
             {
                 yield return new ValidationResult("Get out of here Dee");
             }
         }
    }