1

Here is class Report. I want to make Comment and ReasonIds required if value of Score is less than 4. I can't use attribute validation because you can't use field as attribute argument. How can i validate these fields in ASP.NET MVC core application?

public class Report
{
    public int Score { get; set; }
    public string Comment { get; set; }
    public int[] ReasonIds { get; set; }
}
Lorenzo Isidori
  • 1,809
  • 2
  • 20
  • 31
  • 2
    Possible duplicate of [Custom validation attribute that compares the value of my property with another property's value in my model class](https://stackoverflow.com/questions/11959431/custom-validation-attribute-that-compares-the-value-of-my-property-with-another) – Marco Aug 19 '19 at 08:07

1 Answers1

1

This should give you what you are looking for.

public class Report : ValidationAttribute
    {
        public int Score { get; set; }
        public string Comment { get; set; }
        public int[] ReasonIds { get; set; }

        protected override ValidationResult IsValid(
        object value, ValidationContext validationContext)
        {
            if(Score < 4 && (string.IsNullOrEmpty(Comment) || ReasonIds.Count() < 1))
            {
                return new ValidationResult(GeScoreErrorMessage());
            }
            return ValidationResult.Success;
        }

        private string GeScoreErrorMessage()
        {
            return $"If Score < 4 Comment and Reasons must be provided";
        }
    }
Edney Holder
  • 1,140
  • 8
  • 22