1

I have three classes in my code - Parent, Child1, and Child2 - and I want to validate property Child2.B only when property Child1.A has a value. Because A and B are in different classes, I'm not sure how to verify A has a value. For example:

public class Parent {
  public Child1 C1 { get; set; }
  public Child2 C2 { get; set; }
}

public class Child1 {
  public string A { get; set; }
}

public class Child2 {
  [IsRequiredOnlyWhenAIsNotNull]
  public string B { get; set; }
}

I could perform the validation explicitly; however, I may have quite a few of these sorts of checks so using an attribute would be more convenient.

Benjamin U.
  • 580
  • 1
  • 3
  • 16
  • I try to avoid such a data separation model, but if I wanted to solve your problem, I would create a validator for `Parent` class and move all specified logic in it. – Ivan Khorin Oct 12 '21 at 15:45
  • may be try [this](https://stackoverflow.com/questions/54064308/how-to-perform-validation-of-a-model-of-an-inherited-class-when-its-base-class-a) approach – huMpty duMpty Oct 12 '21 at 15:45
  • If you want to custom required attribute to achieve your requirement, it seems to be impossible. Because ValidationContext can only get the current instance(Child2 here). Even if you put these properties to the same model/view model you can achieve your requirement by custom required attribute. – Rena Oct 13 '21 at 08:52

0 Answers0