I'm using IValidatableObject to validate a complex object in the following scenario.
public class Foo {
[Required]
public Bar Foobar { get; set; }
}
public class Bar : IValidatableObject {
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
// check if the current property instance is decorated with the Required attribute
if(TheAboveConditionIsTrue) {
// make sure the Name property is not null or empty
}
}
}
I don't know if this is the best way to do this, if not I'm happy to take comments on other ways of solving the validation.
Create an abstract base class for
Foo
that implementsIValidatableObject
and make itsValidate()
method virtual:Now implement your base class as either
FooRequired
orFooNotRequired
:Your
Bar
class would still look something like this:Usage: