2

I can validate Data Annotation and IValidatableObject when these one are on simple objects. However, in scenario where an object has a property that has to be validated, things get wrong.

public class BaseClass
{
    public IEnumerable<ValidationResult> Validate()
    {
        var results = new List<ValidationResult>();
        var validationContext = new ValidationContext(this, null, null);
        Validator.TryValidateObject(this, validationContext, results, true);
        return results;
    }
}

public class Class1 : BaseClass, IValidatableObject
{
    public Class1()
    {
        Property1 = new Class2();
    }
    public Class2 Property1 { get; set; }
    //[Required]
    public string AString1 { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        var e = new ValidationResult("Error from class1");
        var s = Property1.Validate();
        var r = new List<ValidationResult>(s) { e };
        return r;
    }
}

public class Class2 :BaseClass, IValidatableObject
{
    public Class2()
    {
        Property2 = new Class3();
    }
    public Class3 Property2 { get; set; }
    //[Required]
    public string AString2 { get; set; }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        yield return new ValidationResult("Error from class2");
    }
}

public class Class3:BaseClass
{
    //[Required]
    public string AString3 { get; set; }
}
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var s = new Class1();
        var results = s.Validate();
        Assert.AreEqual(5, results.Count());
    }
}

This small code snippet return 2 errors. The two that are from the Validate method of IValidatableObject. This is fine. However, if I uncomment the three "Required" data annotation I should have 5 errors (2 from Validate method and 3 froms Data Annotation).

Why when I uncomment the three data annotation that I have only one error "The AString1 field is required." which is the first class data annotation?

How can I have the five errors to be returned?

jpaugh
  • 6,634
  • 4
  • 38
  • 90
Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341

1 Answers1

-1

I believe there is because of the code in DataAnotations.Validator.GetObjectValidationErrors that kicks out after the first property error, short-circuiting the rest of validation rules. You can get around this by doing all validations inside Validate() method.

Sergey Barskiy
  • 1,761
  • 2
  • 15
  • 17
  • Yes I understand but DataAnnotation is interesting for quick re usability and to have validation client side too. I am wondering if they are a way to make it works correctly. – Patrick Desjardins Feb 24 '14 at 17:13