How to add multiple IF conditions in one rule?
Asked Answered
D

2

5

If I have the following rule:

if (a == true && b == 0)
   return errorsenum.somerror1;
else if (b < c)
   return errorsenum.somerror2;

How can I implement the above as a FluentValidation rule?

EDIT:

Would these 2 rules work?

RuleFor(x => x.b).GreaterThan(0).When(x => x.a);
RuleFor(x => x.b).GreaterThanOrEqualTo(x => x.c);
Dell answered 20/4, 2016 at 12:4 Comment(3)
you may get the error all the code path should return a value; could you please post the method?Millennium
@un-lucky The above is just pseudocode of how the rule is designed. I need the rule as a FluentValidation rule.Dell
So the problem is that only one needs to be true, and then return different validation errors?Chaldea
D
11

You are basically there. I think this is what you want:

RuleFor(x => x.b).GreaterThan(0).When(x => x.a).WithMessage("SomeError1");
RuleFor(x => x.b).GreaterThanOrEqualTo(x => x.c).When(x => !x.a).WithMessage("SomeError2");

So just filter the second rule so it only runs when "a" is false and also add the custom message to each rule.

Fluent validation always runs down all your rules, even if the first one fails, so you need to keep using When() if you want to be selective.

If you have a bunch of rules to validate when a == true, you can use this pattern instead:

When(x => x.a, () =>
{
    RuleFor(x => x.b).GreaterThan(0).WithMessage("SomeError1");
    RuleFor(x => x.c).LessThan(0).WithMessage("SomeError3");
});
Dissociation answered 5/5, 2016 at 16:30 Comment(0)
A
1

another note:

RuleFor(x => x).Empty().When(x => x.Username == null && x.Password == null).WithMessage("Şifre ve Parola Boş geçilemez");
Aptitude answered 18/7, 2023 at 8:12 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.