Reputation: 93444
I have some complex validation scenarios that I need some help with.
I have a ViewModel that looks like this:
public class FooModel {
public class BarModel {
public string Name {get;set;}
public DateTime? BirthDate {get;set;}
}
public List<BarModel> Bars {get;set;}
// 10 BarModels added in controller
public FooModel() { Bars = new List<BarModel>(); }
public bool Choose1 {get;set;}
public bool Choose2 {get;set;}
}
Now, depending on the value of Choose1, I need to either valudate that all BarModel's have data set (Required validation) if Choose1 is true, or if Choose1 is false then the first two items in the list will be ignored.
Second, if Choose2 is true, then I only want to collect birthdate for each item in Bars, and ignore the Name property.
I've looked at a custom attribute, but there doesn't seem to be a good way to apply it to the nested class and get at the values in the parent class. I've also not found a way that I can easily only validate some items in a collection.
Any suggestions?
EDIT:
I've also considered IValidatableObject, but I am interested in a solution that will also work client side, if possible. Are there any other options?
Upvotes: 3
Views: 643
Reputation: 6771
Write your own validation with implementing IValidatableObject
public class FooModel : IValidatableObject {
public class BarModel {
public string Name {get;set;}
public DateTime? BirthDate {get;set;}
}
public List<BarModel> Bars {get;set;}
// 10 BarModels added in controller
public FooModel() { Bars = new List<BarModel>(); }
public bool Choose1 {get;set;}
public bool Choose2 {get;set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (Choose1)
{
// do your validation and return result if needed:
yield return new ValidationResult("The title is mandatory.");
}
// ...
}
}
Upvotes: 2