I have these 2 entities:
public class Parent
{
public ICollection<Child> Children {get; set;}
}
public class Child
{
public decimal Percentage {get; set;}
}
I would like to add a validation rule so that the total Percentage
of all children is 100. How can I add this rule in the following validator?
public ParentValidator()
{
RuleFor(x => x.Children).SetCollectionValidator(new ChildValidator());
}
private class ChildValidator : AbstractValidator<Child>
{
public ChildValidator()
{
RuleFor(x => x.Percentage).GreaterThan(0));
}
}
Use predicate validator for collection property:
public class ParentValidator : AbstractValidator<Parent>
{
public ParentValidator()
{
RuleFor(x => x.Children)
.SetCollectionValidator(new ChildValidator())
.Must(coll => coll.Sum(item => item.Percentage) == 100);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With