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);
3
  • you may get the error all the code path should return a value; could you please post the method? Commented Apr 20, 2016 at 12:07
  • @un-lucky The above is just pseudocode of how the rule is designed. I need the rule as a FluentValidation rule. Commented Apr 20, 2016 at 12:08
  • So the problem is that only one needs to be true, and then return different validation errors? Commented Apr 20, 2016 at 12:20

2 Answers 2

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");
});
Sign up to request clarification or add additional context in comments.

Comments

1

another note:

RuleFor(x => x).Empty().When(x => x.Username == null && x.Password == null).WithMessage("Şifre ve Parola Boş geçilemez");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.