ValidationResults on TryValidateObject is null

483 views Asked by At

I am trying to get my head around data annotations.

Here's my class:

public class Video
{
    [Required]
    public string Title {get; set; }

    public List<ValidationResult> ValidationResults { get; set; }

    public bool IsValid()
    {
        var context = new ValidationContext(this, null, null);
        return Validator.TryValidateObject(this, context, this.ValidationResults);
    }
}

If I create an object of type Video without setting a Title, IsValid returns false (correct!), but the ValidationResults of the objects are null. Aren't they suppose to contain a ValidationResult with an error message saying that video is required or something?

1

There are 1 answers

0
Kevin Wong On

To fix the issue, the validateAllProperties parameter needs to be set as true. e.g.

Validator.TryValidateObject(model, validationContext, ValidationResults, true)