skip to content

With FluentValidation, how do you write order rules that depend on another property, using When, Unless, Must or Custom?

level: middleimportance: should knowfreq 55%

answer

  1. conditions decide whether a rule runs
  2. the condition covers the chain so far
  3. a predicate that sees the whole command
  4. several failures from one rule

basics

~20 s

When and Unless decide whether a rule runs; a trailing When covers every validator before it in the chain. Must with the root object, or a comparison validator taking a lambda, checks one field against another; Custom adds several failures.

solid answer

~40 s

I separate two ideas. A **condition** decides whether a rule runs: `.When(x => x.DeliveryMethod == DeliveryMethod.Express)` or its inverse `.Unless(...)`, and a top-level `When(cond, () => { ... }).Otherwise(() => { ... })` groups several rules. A trailing `When` applies to every validator before it in the same chain unless I pass `ApplyConditionTo.CurrentValidator`. A **cross-field check** produces a failure: comparison validators accept a lambda, as in `GreaterThan(x => x.OrderDate)`, and `Must((command, value) => ...)` gives the predicate the whole command. When one rule must report several problems, or name a different property, I use `Custom((value, context) => context.AddFailure(...))`. Repeated logic becomes an extension method on `IRuleBuilder<T, TProperty>`.

code

csharp · 39 lines
csharp
using FluentValidation;

public enum DeliveryMethod { Standard, Express }

public class CreateOrderCommand
{
    public DeliveryMethod DeliveryMethod { get; set; }
    public string? ContactPhone { get; set; }
    public DateTime OrderDate { get; set; }
    public DateTime? RequestedDeliveryDate { get; set; }
    public decimal Subtotal { get; set; }
    public decimal Discount { get; set; }
    public List<string> CouponCodes { get; set; } = new();
}

public class CreateOrderCommandValidator : AbstractValidator<CreateOrderCommand>
{
    public CreateOrderCommandValidator()
    {
        RuleFor(x => x.ContactPhone)
            .NotEmpty()
            .When(x => x.DeliveryMethod == DeliveryMethod.Express);

        RuleFor(x => x.RequestedDeliveryDate)
            .GreaterThan(x => x.OrderDate);          // a null date passes comparison validators

        RuleFor(x => x.Discount)
            .Must((command, discount) => discount <= command.Subtotal)
            .WithMessage("Discount cannot exceed the subtotal.");

        RuleFor(x => x.CouponCodes).Custom((codes, context) =>
        {
            if (codes.Count > 3)
                context.AddFailure("At most three coupon codes are allowed.");
            if (codes.Distinct().Count() != codes.Count)
                context.AddFailure("Coupon codes must not repeat.");
        });
    }
}

go deeper

for a junior

Recall that When and Unless switch rules on or off, and that Must takes a predicate that returns true for valid values.

for a middle

Explain the default scope of a trailing When, the top-level When with Otherwise, Must with the root object, comparison validators taking a lambda, and why Custom can add several failures.

for a senior

Show judgement about where a cross-field failure should be attached so the client highlights the right field, and why a condition must never stand in for a rule.

for a principal

Push for named extension methods for business checks reused across commands, so a rule such as discount limits is defined once and reviewed once.

Most real order rules are not about one field in isolation. Express delivery needs a phone number, a requested delivery date must follow the order date, a discount is allowed only for some customers. FluentValidation, the .NET library that holds validation rules in a separate validator class, offers two families of tools for this, and mixing them up is the usual mistake. ## Conditions: whether a rule runs A **condition** never produces a failure by itself. It only decides whether the validators it guards are executed. - `When(predicate)` runs the guarded validators only when the predicate returns `true`; `Unless(predicate)` is its inverse. - The predicate receives the **whole object** being validated, so it can look at any property. - Placed at the end of a chain, the condition applies to **all validators before it** in that `RuleFor` call. That default is `ApplyConditionTo.AllValidators`. - To guard only the validator immediately before it, pass `ApplyConditionTo.CurrentValidator`, and do so on **every** condition in that chain, because one without it still covers everything before it. ```csharp RuleFor(x => x.ShippingAddress.Phone) .NotEmpty() .MaximumLength(20) .When(x => x.DeliveryMethod == DeliveryMethod.Express && x.ShippingAddress != null); ``` Here both `NotEmpty` and `MaximumLength` are skipped for standard delivery. For several rules sharing one condition there is a **top-level** form: ```csharp When(x => x.DeliveryMethod == DeliveryMethod.Express, () => { RuleFor(x => x.RequestedDeliveryDate).NotNull(); RuleFor(x => x.ShippingAddress).NotNull(); }).Otherwise(() => { RuleFor(x => x.RequestedDeliveryDate).Null(); }); ``` `Otherwise` declares the rules that run when the condition is false. `WhenAsync` and `UnlessAsync` exist for conditions that must await something, and they oblige callers to use `ValidateAsync`. ## Cross-field checks: producing a failure When the relationship itself is the rule, it must be a validator, not a condition. 1. **Comparison validators with a lambda.** `GreaterThan`, `GreaterThanOrEqualTo`, `LessThan`, `Equal` and `NotEqual` accept an expression for another property: `RuleFor(x => x.RequestedDeliveryDate).GreaterThan(x => x.OrderDate)`. The default message shows the compared value, and a `{ComparisonProperty}` placeholder can name the other property. The ordering validators (`GreaterThan`, `LessThan` and their `OrEqualTo` forms) treat a null property value as valid, so pair them with `NotNull()` when the value is required. 2. **`Must` with the root object.** `Must(value => ...)` sees only the property; the overload `Must((command, value) => ...)` also receives the command, and a third overload adds the `ValidationContext<T>`. It produces one failure with a predicate-style default message, so pair it with `WithMessage`. 3. **`Custom`.** `Custom((value, context) => { ... })` gives you the context and nothing else: you call `context.AddFailure(...)` yourself, as many times as needed, optionally with a different property name. It is more verbose, and it is the tool when one check yields several messages. 4. **A `PropertyValidator<T, TProperty>` subclass.** For complex logic reused widely, a class overriding `IsValid` and a default message template, attached with `SetValidator`. The documentation calls this an advanced technique that is usually unnecessary. | Need | Tool | Failures it can add | |---|---|---| | skip rules for some orders | `When` / `Unless` / `Otherwise` | none by itself | | compare two properties | `GreaterThan(x => x.Other)` and friends | one | | arbitrary predicate on the command | `Must((cmd, v) => ...)` | one | | several messages, other property names | `Custom` with `AddFailure` | any number | | reusable named check | extension method on `IRuleBuilder` | depends on the inner validator | ## Making rules reusable A predicate used in several validators is wrapped as an **extension method** on `IRuleBuilder<T, TProperty>` that calls `Must` internally and returns its options, so it chains like a built-in validator. Inside the overload of `Must` that takes the context, `context.MessageFormatter.AppendArgument("Max", max)` adds a custom placeholder that `WithMessage("{PropertyName} allows at most {Max} items.")` can use. ## Pitfalls interviewers probe - Using `When` to express a rule. `RuleFor(x => x.Discount).GreaterThan(0).When(x => x.Discount > x.Subtotal)` does not reject an oversized discount; it only changes when the `GreaterThan` check runs. - Forgetting the default scope of a trailing `When`, so a format check that should always run is skipped together with a conditional `NotEmpty`. - Putting cross-field logic on the wrong property, so the failure's `PropertyName` points at a field the user did not touch. Attach the rule to the field the user must change. - Reaching for `DependentRules` for ordering. It runs nested rules only when the parent rule passed, but an author's note in the library's documentation says `When` combined with cascade modes is often simpler to read.

  • With FluentValidation, how do you apply a When to only the last validator in a chain?
    Pass `ApplyConditionTo.CurrentValidator` as the second argument: `.Matches(pattern).When(x => x.IsInternational, ApplyConditionTo.CurrentValidator)`. Without it the condition defaults to `ApplyConditionTo.AllValidators` and covers every validator declared before it in that rule. If the chain has several conditions, each one needs the argument, or the one that lacks it reaches back over the whole chain.
  • With FluentValidation, when is Custom a better choice than Must?
    When one check must report more than one problem, or attach its failure to a property other than the one in `RuleFor`. `Custom` hands you the `ValidationContext` and you call `context.AddFailure` as often as needed, with an optional property name. `Must` returns a single boolean and so yields at most one failure, but it is shorter and gets default message handling, so it stays the first choice.

  • A When condition adds a failure when its predicate returns false.
  • A trailing When guards only the validator written just before it.
  • Must can only see the value of the property in RuleFor.
  • Comparing two properties requires writing a custom PropertyValidator class.
  • Custom and Must are interchangeable, both adding at most one failure.