3

I am using IValidatableObject validation for entities with e.g. following code:

public class OuterObj : IValidatableObject
{    
    public int ID { get; set; }

    public string Name { get; set; }

    public IEnumerable<InnerObj> InnerObjList { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (this.ID <= 0)
        {
            yield return new ValidationResult("", new[] { nameof(this.ID) });
        }
    }
}

public class InnerObj : IValidatableObject
{
    public int ID { get; set; }

    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if (this.ID <= 0)
        {
            yield return new ValidationResult("", new[] { nameof(this.ID) });
        }
    }
}

In this case when I am validating the outerObj, when there are innerObj present it validates only the innerobj and not the outerobj. It doesn't reach the outerobj validate method in case of presence of innerobj.

I would like to validate both when innerobj present. Please help me with how its done. Why does it not validate the outerobj?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
NehaPatil
  • 31
  • 1

1 Answers1

-1

MVC 5.2.3

If the parent class has properties with validation attributes, and any of those properties have been evaluated as invalid, then the IValidatableObject.Validate implementation will not be invoked on the parent class.

This seems to be some sort of short-cutting that MVC is performing for model validation.

Your example does not show validation attribute(s) in the parent class - I'm assuming they were left out.

The workaround is remove validation attributes on properties in the parent class, and only implement validation in the parent class through the IValidatableObject interface.

Aaron Hudon
  • 5,280
  • 4
  • 53
  • 60
  • If I use only IValidatableObject on both the parent and child object (with no attributes whatsoever) in MVC 5.2.3, the behaviour is still the same. – Stephan B Dec 12 '19 at 07:16