Search code examples
c#.netfluentvalidation

Is there an existing validation rule that works on the sum of several properties, where the sum is not a property?


Let's say we have a request object :

public class ExampleRequest {
    public int? A { get; set; }
    public int? B { get; set; }
    public int? C { get; set; }
    public int? D { get; set; }
    ...
}

and there exists an API rule where 1 ≤ Sum(a, b, c, d) ≤ 10.

  • Sum(a, b, c, d) must be at least 1 and at most 10.

I've tried implementing this rule like so:

RuleFor(x => x.A ?? 0 + x.B ?? 0 + x.C ?? 0 + x.D ?? 0)
    .GreaterThan(0)
    .LessThanOrEqualTo(10);

This rule didn't work.

a) How can I craft a ruleset to handle this kind of scenario?

b) Is it even possible to create a rule in this case-- where the rule isn't necessarily applied to a property of the object, but rather some function applied to several properties?

Edit: Edited code blocks to represent the cause of the error.


Solution

  • Your error is because Operator precedence. + has higher precedence than ??. This should work:

    RuleFor(x => (x.a ?? 0) + (x.b ?? 0) + (x.c ?? 0) + (x.d ?? 0) )
                .GreaterThan(0)
                .LessThanOrEqualTo(10);