Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

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?

Upvotes: 7

Views: 3241

Answers (1)

Adem Catamak
Adem Catamak

Reputation: 2009

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);

Upvotes: 4

Related Questions