简体   繁体   中英

FluentValidation require one out of three values

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?

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM