skip to content

With FluentValidation, how do you validate a create-order command's nested shipping address and every item in its line-item list?

level: middleimportance: must knowfreq 60%

answer

  1. reuse a validator inside another
  2. one rule, many elements
  3. null children are skipped
  4. indexed property paths in failures

basics

~20 s

Attach an AddressValidator with SetValidator (or inline ChildRules) for the shipping address, and use RuleForEach with SetValidator or ChildRules for line items. Null children and null lists are skipped, so add NotNull; failures carry paths like LineItems[1].Quantity.

solid answer

~40 s

For the nested object I write a separate `AddressValidator` and attach it with `RuleFor(x => x.ShippingAddress).SetValidator(new AddressValidator())`, or declare the rules inline with `ChildRules`. For the list I use `RuleForEach(x => x.LineItems)`, followed by `SetValidator(new LineItemValidator())` or `ChildRules`, which runs the same checks on every element. All failures land in one `ValidationResult` with full paths such as `ShippingAddress.Postcode` and `LineItems[1].Quantity`. Two traps: a child validator is skipped when the property is null and `RuleForEach` does nothing for a null or empty list, so I add `NotNull()` on the address and `NotEmpty()` on the list as separate rules; and a dotted rule like `RuleFor(x => x.ShippingAddress.Postcode)` has no automatic null guard, so it needs a `When` condition.

code

csharp · 46 lines
csharp
using FluentValidation;

public class Address
{
    public string Line1 { get; set; } = "";
    public string Postcode { get; set; } = "";
    public string Country { get; set; } = "";
}

public class LineItem
{
    public string Sku { get; set; } = "";
    public int Quantity { get; set; }
}

public class CreateOrderCommand
{
    public Address? ShippingAddress { get; set; }
    public List<LineItem> LineItems { get; set; } = new();
}

public class AddressValidator : AbstractValidator<Address>
{
    public AddressValidator()
    {
        RuleFor(x => x.Line1).NotEmpty();
        RuleFor(x => x.Postcode).NotEmpty().MaximumLength(10);
        RuleFor(x => x.Country).NotEmpty().Length(2);
    }
}

public class CreateOrderCommandValidator : AbstractValidator<CreateOrderCommand>
{
    public CreateOrderCommandValidator(IValidator<Address> addressValidator)
    {
        RuleFor(x => x.ShippingAddress).NotNull();                 // a null child is otherwise skipped
        RuleFor(x => x.ShippingAddress).SetValidator(addressValidator);

        RuleFor(x => x.LineItems).NotEmpty();                      // RuleForEach ignores an empty list
        RuleForEach(x => x.LineItems).ChildRules(item =>
        {
            item.RuleFor(i => i.Sku).NotEmpty();
            item.RuleFor(i => i.Quantity).GreaterThan(0);
        });
    }
}

go deeper

for a junior

Recall the tools: SetValidator or ChildRules for one nested object, RuleForEach for every element of a list, and that failures show paths like LineItems[1].Quantity.

for a middle

Explain the null behaviour: a null child is skipped, an empty list produces nothing from RuleForEach, and a dotted RuleFor throws without a When guard. Say which separate rules close each gap.

for a senior

Discuss when a child validator deserves its own class and constructor injection, how rule sets flow into children, and how indexed paths let tests and clients pinpoint a failing line item.

for a principal

Set the convention: shared value types like addresses get one validator reused everywhere, while single-use shapes stay inline, so a rule change lands in exactly one place.

A create-order command is rarely flat. It usually holds a **nested object**, such as a shipping address, and a **collection**, such as the order's line items. FluentValidation, the .NET library that keeps validation rules in separate validator classes, has dedicated tools for both, and the details of what happens with null and empty values are where interview answers separate. ## Nested objects: SetValidator and ChildRules A **child validator** is an ordinary `AbstractValidator<Address>` reused inside the parent's validator. - `RuleFor(x => x.ShippingAddress).SetValidator(new AddressValidator())` runs every rule of `AddressValidator` against the address and merges its failures into the parent's single `ValidationResult`. - `ChildRules(a => { a.RuleFor(x => x.Postcode).NotEmpty(); })` declares the same kind of rules **inline**, which suits a small type that is validated in only one place. - If the child validator needs services, take it as a constructor parameter, for example `IValidator<Address>`, and pass that to `SetValidator`. Two behaviours to know: 1. **A null child is skipped.** If `ShippingAddress` is null, the child validator is not executed and no failure is added. A required address therefore needs its own `RuleFor(x => x.ShippingAddress).NotNull()`. 2. **A dotted rule has no null guard.** Writing `RuleFor(x => x.ShippingAddress.Postcode).NotEmpty()` dereferences `ShippingAddress` directly. When the address is null, the rule throws a `NullReferenceException` whose message suggests adding a `When` condition. Use `.When(x => x.ShippingAddress != null)` or prefer a child validator. ## Collections: RuleForEach `RuleForEach(x => x.LineItems)` creates one rule that runs its validators against **each element**. - For simple elements, chain built-in validators directly: `RuleForEach(x => x.CouponCodes).NotEmpty()`. - For complex elements, chain `SetValidator(new LineItemValidator())` or `ChildRules(...)`. - `Where(item => ...)` placed straight after `RuleForEach` filters which elements are validated, for example skipping gift items. - The `{CollectionIndex}` placeholder puts the element's zero-based index into a custom message: `WithMessage("Line {CollectionIndex} needs a SKU.")`. A **null or empty list** produces no failures from `RuleForEach`, because there is nothing to iterate. "At least one line item" is a rule about the whole list, so it is written with `RuleFor`: ```csharp RuleFor(x => x.LineItems).NotEmpty(); RuleForEach(x => x.LineItems).SetValidator(new LineItemValidator()); ``` FluentValidation also lets you combine the two with `RuleFor(...).ForEach(...)`, but its documentation recommends two separate rules as clearer. ## Property paths in failures FluentValidation builds each failure's `PropertyName` from the chain of properties it walked: | Rule | Failing value | `PropertyName` on the failure | |---|---|---| | child validator on `ShippingAddress` | empty postcode | `ShippingAddress.Postcode` | | `RuleForEach` on `LineItems` with `ChildRules` | second item's quantity is 0 | `LineItems[1].Quantity` | | `RuleForEach` on `CouponCodes` | third code is blank | `CouponCodes[2]` | | `RuleFor(x => x.LineItems).NotEmpty()` | empty list | `LineItems` | Indexes are **zero-based**, so the second element is `[1]`. These paths are what a test asserts on and what a client uses to highlight the right field. ## SetValidator or ChildRules | Concern | `SetValidator` with a class | `ChildRules` inline | |---|---|---| | Reuse across commands | yes, one `AddressValidator` everywhere | no, rules live in one parent | | Dependencies from DI | via the parent's constructor | only what the parent captured | | Testing alone | test `AddressValidator` directly | only through the parent | | Readability for tiny types | an extra class | everything on one screen | A reasonable rule of thumb: an address that appears on orders, customers and invoices earns its own validator; a three-field line item used only here can stay inline. ## Points that come up in follow-ups - **Rule sets flow down.** A child attached with `SetValidator` inherits the rule-set selection of the parent call by default, so the child's rules must be in the same rule set to run unless `SetValidator` is given an explicit rule-set override. - **Cascade applies per rule.** A `Cascade(CascadeMode.Stop)` on a `RuleForEach` rule stops the whole collection rule at the first failing element, not just that element's checks. - **Messages stay specific.** Because each failure carries the indexed path, one result can report "item 0 lacks a SKU" and "item 3 has quantity 0" together.

  • With FluentValidation, how do you validate only some elements of a collection, such as skipping gift items?
    Call `Where` directly after `RuleForEach`, for example `RuleForEach(x => x.LineItems).Where(i => !i.IsGift).SetValidator(new LineItemValidator())`. Elements for which the predicate returns false are not validated, and the indexes in failure paths still refer to their position in the original list. `WhereAsync` is the asynchronous counterpart and makes the validator require `ValidateAsync`.
  • With FluentValidation, why might a rule for ShippingAddress.Postcode throw instead of failing?
    Because `RuleFor(x => x.ShippingAddress.Postcode)` evaluates the whole member chain, and FluentValidation adds no null check for intermediate objects. With a null address the lambda throws, and the library rethrows a `NullReferenceException` that suggests a `When` condition. Guard it with `.When(x => x.ShippingAddress != null)`, or validate the address through a child validator, which is skipped for null.

  • A child validator reports the address as missing when ShippingAddress is null.
  • RuleForEach on an empty list fails, so no NotEmpty rule is needed.
  • FluentValidation adds null checks to dotted paths like ShippingAddress.Postcode.
  • Collection failure paths use one-based indexes such as LineItems[1] for the first item.
  • Nested rules have to be copied into the parent validator by hand.