Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate collection using sum on a property

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));
    }
}
like image 984
Ivan-Mark Debono Avatar asked Oct 19 '22 10:10

Ivan-Mark Debono


1 Answers

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);
    }
}
like image 149
Evgeny Levin Avatar answered Nov 15 '22 06:11

Evgeny Levin