Below is a simplified version of my problem.
I can not flatten the model. There is a List of "children" that I need to validate a birthday.
I can not seem to reference the date in the Parent class and was wondering how this is done in Fluent Validation?
Model
[Validator(typeof(ParentValidator))]
public class Parent
{
public string Name { get; set; }
public DateTime Birthdate { get; set; }
public List<Child> Children { get; set; }
}
public class Child
{
public string ChildProperty{ get; set; }
public DateTime Birthdate { get; set; }
}
Validator
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(model => model.Name).NotEmpty();
RuleForEach(model => model.Children).SetValidator(new ChildValidator());
}
}
public class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
RuleFor(model => model.ChildProperty).NotEmpty();
//Compare birthday to make sure date is < Parents birthday
}
}
Create a custom property validator like this
Add rules like this
Alternative to the Custom Property validator is to use the Custom method:
Crude way of showing indicies that failed: (should probably be name of some other identifier)
There is a way easier way to do this using set child validator:
Nowadays the answer by @johnny-5 can be simplified even further by using the
SetCollectionValidator
extension method and passing the parent object to the child validator: