Confirm collection using property amount

I have two objects:

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 all children is 100. How do I add this rule to the next validator?

 public ParentValidator() { RuleFor(x => x.Children).SetCollectionValidator(new ChildValidator()); } private class ChildValidator : AbstractValidator<Child> { public ChildValidator() { RuleFor(x => x.Percentage).GreaterThan(0)); } } 
+5
source share
1 answer

Use the predicate checker for the collection property:

 public class ParentValidator : AbstractValidator<Parent> { public ParentValidator() { RuleFor(x => x.Children) .SetCollectionValidator(new ChildValidator()) .Must(coll => coll.Sum(item => item.Percentage) == 100); } } 
+1
source

All Articles