Home > Software design >  FluentValidation require one out of three values
FluentValidation require one out of three values

Time:06-24

Using fluent validation and verifying if at least one variable out of three is > 0. I have tried verifying with a when otherwise statement but I can't add another otherwise statement.

        When(c => c.var1!= null || c.var2!= null || c.var3!= null, () =>
        {
            RuleFor(c => c.var1).GreaterThan(0)
            .WithMessage("One of these fields, var1, var2, or var3, are required.");
        }).Otherwise(() =>
        {
            RuleFor(c => c.var2).GreaterThan(0);
        });
// I would like to verify a third var but can't stack otherwise statements

If I would like to verify that one of var1, var2, var3 is > 0 what changes should I make?

CodePudding user response:

If you use a when statement you can verify all 3 variables with only one validation message sent. There is such thing as dependent rules but that is more complicated.

RuleFor(c => c.var1).NotNull()
  .WithMessage("At least one is required");

RuleFor(c => c.var2).NotNull()
  .When(c => c.var2!= null)
  .WithMessage("At least one is required");

RuleFor(c => c.var3).NotNull()
  .When(c => c.var1!= null && c.var2!= null)
  .WithMessage("At least one is required");
  • Related