I've just started using FluentValidation v9.x and am wondering how to go about validating rules in a collection.
Basically if I have a collection of substances
public class Substance
{
public int? SubstanceId { get; set; }
public string SubstanceName { get; set; }
public decimal? SubstanceAmount { get; set; }
public int? SubstanceUnitId { get; set; }
public int? SubstanceRouteId { get; set; }
public DateTimeOffset? SubstanceTime { get; set; }
}
and I want to validate that:
- if SubstanceAmount and SubstanceUnitId has values, and
- if SubstanceRouteId has a value, and
- if SubstanceTime has a value on any of the substance items.
I'm looking to send back one error message for each of the rules if they fail, not for each substance, which is what is happening now with the following:
RuleForEach(x => x.SubstanceList).SetValidator(new SubstanceValidator(RuleSetsToApply));
public class SubstanceValidator : AbstractValidator<Substance>
{
public SubstanceValidator(List<ValidationRule> RuleSetsToApply)
{
string ruleSetName = "SubstanceAmountUnit";
RuleSet(ruleSetName, () => {
RuleFor(x => x.SubstanceAmount).NotNull().NotEmpty();
RuleFor(x => x.SubstanceUnitId).NotNull().NotEmpty().GreaterThan(0);
});
ruleSetName = "SubstanceIngestion";
RuleSet(ruleSetName, () => {
RuleFor(x => x.SubstanceTime).NotNull().NotEmpty();
});
ruleSetName = "SubstanceRoute";
RuleSet(ruleSetName, () => {
RuleFor(x => x.SubstanceRouteId).NotNull().NotEmpty().GreaterThan(0);
});
}
}
So if I have five substances and
- the first substance fails Rule #2,
- the third fails Rule #1 and #2 and
- the fourth fails on the Rule #3,
I would expect one error for each rule to be returned, even though Rule #2 has failed twice.
How can I accomplish this?
