Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

How can I fix this?

like image 887
Ivan-Mark Debono Avatar asked Aug 22 '18 13:08

Ivan-Mark Debono


Video Answer


1 Answers

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);
like image 73
Adem Catamak Avatar answered Sep 30 '22 13:09

Adem Catamak