0

I have following object

public class TestClass
{
    [Required]
    public int TestId { get; set; }
}

I validate using:

List<ValidationResult> results = new List<ValidationResult>();
var vc = new ValidationContext(data);
if (Validator.TryValidateObject(data, vc, results, true))
    return;

This validates perfectly fine if data is of type TestClass but not when I pass list of TestClass items (List<TestClass>)

How can I validate the items withing a list without iterating?

Mighty Badaboom
  • 6,067
  • 5
  • 34
  • 51
pantonis
  • 5,601
  • 12
  • 58
  • 115

2 Answers2

0

TryValidateObject expects an object and not a list of. You have to write a helper class. Furthermore it even doesn't recursively check the Validation. See this SO question for more...

Peter Schneider
  • 2,879
  • 1
  • 14
  • 17
0

Usually I add the Validate method in the class that I need to validate, and I foreach the property that has a list of T.

For example:

    public class ClassToValidate : IValidatableObject
    {
        // Property with a non-custom type
        [Required(AllowEmptyStrings = false, ErrorMessage = "\"Language\" is required. It can not be empty or whitespace")]
        public string Language { get; set; }

        // Property with a custom type
        public Source Source { get; set; }

        // Property with a custom type list
        public List<Streaming> StreamingList { get; set; } = new List<Streaming>();

        // Validate method that you need to implement because of "IValidatableObject"
        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            // The validation result that will be returned
            List<ValidationResult> result = new List<ValidationResult>();

            // Language doesn't need to be added in the Validate method because it isn't a custom object

            // Custom single T object to be validated
            Validator.TryValidateObject(Source, new ValidationContext(Source), result, true);

            // Custom list<T> object to be validated
            foreach (var streaming in StreamingList)
            {
                Validator.TryValidateObject(streaming, new ValidationContext(streaming), result, true);
            }

            return result;
        }
    }
    public class Source
    {
        [Range(16, 192, ErrorMessage = "\"Bitrate\" must be between 16 and 192")]
        public int? Bitrate { get; set; }

        public string Codec { get; set; }
    }
    public class Streaming
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "\"Url\" can not be empty")]
        public string Url { get; set; }

        [Range(0, 1000, ErrorMessage = "\"Offset\" must be between 0 and 1000")]
        public int Offset { get; set; }
    }

MarGraz
  • 61
  • 9