How to validate collection items using RuleForEach
How to validate collection items using RuleForEach
I have been using (successfully) the following validation:
RuleFor(x => x.Items)
.SetCollectionValidator(new ItemValidator())
.Must(coll => coll.Sum(item => item.Percentage) == 100)
.When(x => x.Items != null);
As the above SetCollectionValidator
is (will be) deprecated, I changed it to:
SetCollectionValidator
RuleForEach(x => x.Items)
.SetValidator(new ItemValidator())
.Must(coll => coll.Sum(item => item.Percentage) == 100)
.When(x => x.Items != null);
However, Sum
is not recognized anymore.
Sum
How can I fix this?
1 Answer
1
You can use two separate rules. One of them is validate item, and other one is for validation of collection.
RuleForEach(x => x.Items)
.SetValidator(new ItemValidator());
RuleFor(x => x.Items)
.Must(coll => coll.Sum(item => item.Percentage) == 100)
.When(x => x.Items != null);
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.