skip to content

FluentValidation

.NET validation written as a separate rule class with a fluent chain, keeping rules out of the model. Interviewers ask how it compares to data annotations: conditional rules and testability.

questions

6

With FluentValidation, how do you write a validator for a create-order command, and how do NotNull and NotEmpty differ?

level: juniorimportance: must knowfreq 70%

answer

  1. a class per model, not attributes
  2. rules declared in the constructor
  3. a result object, not an exception
  4. null versus blank, empty or default

basics

~10 s

Inherit AbstractValidator<CreateOrderCommand>, declare RuleFor chains in its constructor and call Validate to get a ValidationResult. NotNull rejects only null; NotEmpty also rejects whitespace strings, empty collections and a value type's default, such as 0.

solid answer

~40 s

I write a class that inherits `AbstractValidator<CreateOrderCommand>` and declare one `RuleFor(x => x.Property)` chain per property in its constructor, so the rules live outside the command. Calling `validator.Validate(command)` returns a `ValidationResult` with `IsValid` and an `Errors` list of `ValidationFailure` objects, each carrying `PropertyName`, `ErrorMessage` and `ErrorCode`; `ValidateAndThrow` is the variant that throws a `ValidationException` instead. `NotNull()` fails only when the value is null. `NotEmpty()` also fails for an empty or whitespace-only string, an empty collection and the default of a value type, such as `0`, `Guid.Empty` or a default `DateTime`. So `NotNull()` on a non-nullable `int` can never fail, and a customer ID of three spaces passes `NotNull()` but not `NotEmpty()`.

code

csharp · 40 lines
csharp
using FluentValidation;
using FluentValidation.Results;

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

public class CreateOrderCommand
{
    public string CustomerId { get; set; } = "";
    public int Quantity { get; set; }
    public List<LineItem> LineItems { get; set; } = new();
}

public class CreateOrderCommandValidator : AbstractValidator<CreateOrderCommand>
{
    public CreateOrderCommandValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.Quantity).NotNull();   // an int is never null: this rule cannot fail
        RuleFor(x => x.LineItems).NotEmpty();
    }
}

public static class Demo
{
    public static void Run()
    {
        var command = new CreateOrderCommand { CustomerId = "   ", Quantity = 0 };
        ValidationResult result = new CreateOrderCommandValidator().Validate(command);

        Console.WriteLine(result.IsValid); // False
        foreach (var failure in result.Errors)
            Console.WriteLine($"{failure.PropertyName}: {failure.ErrorCode}");
        // CustomerId: NotEmptyValidator
        // LineItems: NotEmptyValidator
    }
}

go deeper

for a junior

Recall the shape: a class inheriting AbstractValidator of the command, RuleFor chains in the constructor, Validate returning a result with IsValid and Errors. Then the NotNull versus NotEmpty table.

for a middle

Explain why NotNull on a non-nullable int is dead code and why NotEmpty on an int? still accepts 0. Show you read ErrorCode, not the message, to tell failures apart.

for a senior

Talk about choosing checks by intent: NotEmpty for identifiers and required lists, NotNull where empty is legitimate, GreaterThan for amounts. Mention that a null root model throws rather than failing validation.

for a principal

Frame it as a review standard: validators should state intent precisely, and a codebase where every rule is NotNull is one where blank and zero values reach the domain unchecked.

FluentValidation is a .NET library in which validation rules for a type live in a **separate validator class**, written as a chain of method calls, instead of attributes on the model's properties. This answer walks through the smallest useful validator for a create-order command and then the pair of built-in validators that interviewers use to check whether a candidate has actually written one: `NotNull` and `NotEmpty`. ## The validator class A validator is a class that inherits **`AbstractValidator<T>`**, where `T` is the type being validated. The rules are declared in the class's **constructor**: - `RuleFor(x => x.CustomerId)` starts a **rule** for one property, chosen with a lambda so the property name is checked by the compiler and reused in error messages. - Each method chained after it, such as `NotEmpty()`, `MaximumLength(40)` or `GreaterThan(0)`, adds one **validator** (a single check) to that rule. - A rule can hold several validators; by default all of them run even when an earlier one fails. Because the rules sit in their own class, the command itself stays a plain data type. That matters when the command is a record you would rather not decorate, or a type from another assembly you cannot edit. ## Running it and reading the result You create the validator and call **`Validate`**, passing the object: 1. `Validate(command)` runs every rule and returns a **`ValidationResult`**. It does not throw because the data is invalid. 2. `result.IsValid` is `true` only when no rule produced a failure. 3. `result.Errors` is a list of **`ValidationFailure`** objects. Each one has `PropertyName` (for example `CustomerId`), `ErrorMessage` (for example `'Customer Id' must not be empty.`), `ErrorCode` (by default the validator's name, such as `NotEmptyValidator`) and the `AttemptedValue`. 4. If you would rather fail with an exception, `ValidateAndThrow(command)` throws a **`ValidationException`** whose `Errors` property holds the same failures. Passing a null command is different from passing an invalid one: the root model must be non-null, and `Validate` throws an `InvalidOperationException` for a null root. ## NotNull versus NotEmpty These two look interchangeable, and their default English messages are even the same text (`'{PropertyName}' must not be empty.`), but they test different things. | Value of the property | `NotNull()` | `NotEmpty()` | |---|---|---| | `null` | fails | fails | | `""` or `" "` (string) | passes | fails | | an empty list or array | passes | fails | | `0` in an `int` or `decimal` | passes | fails | | `Guid.Empty`, default `DateTime` | passes | fails | | `"C-1042"`, a list with one item, `3` | passes | passes | **`NotNull`** checks exactly one thing: `value != null`. **`NotEmpty`** first rejects null, then rejects a string that is null or whitespace, then a collection with no elements, and finally any value equal to its type's default. Some consequences worth saying out loud in an interview: - `NotNull()` on a non-nullable value type, such as `int Quantity`, **can never fail**, because an `int` is never null. A missing quantity arrives as `0`, so use `NotEmpty()` or, better, `GreaterThan(0)`. - On a **nullable** value type the "default" is null, so `NotEmpty()` on `int?` rejects null but accepts `0`. - For a string, `NotEmpty()` is usually what you mean: a customer ID of spaces is not an ID. - For a collection such as `LineItems`, `NotEmpty()` enforces "at least one item"; `NotNull()` only says the list exists. - `NotNull()` is the right choice when an empty value is legitimate but a missing one is not, for example an optional notes string that may be `""` but must be present. ## A typical first validator ```csharp public class CreateOrderCommandValidator : AbstractValidator<CreateOrderCommand> { public CreateOrderCommandValidator() { RuleFor(x => x.CustomerId).NotEmpty().MaximumLength(40); RuleFor(x => x.Currency).NotEmpty().Length(3); RuleFor(x => x.LineItems).NotEmpty(); RuleFor(x => x.Notes).NotNull(); } } ``` Each line is one rule; the chain reads like a sentence, which is where the "fluent" in the name comes from. ## Common mistakes - Using `NotNull()` everywhere out of habit and letting blank strings, empty lists and zero amounts through. - Expecting `Validate` to throw for bad data and wrapping it in `try`/`catch` instead of checking `IsValid`. - Putting rules in the command's constructor or setters, which mixes data and validation again. - Assuming the error message tells `NotNull` and `NotEmpty` apart; use `ErrorCode` if a client needs to know which check failed.

  • With FluentValidation, does NotEmpty() on a nullable int reject a value of 0?
    No. `NotEmpty()` compares the value with its type's default, and the default of `int?` is null, not 0. So on an `int?` it rejects null and accepts 0. If 0 is invalid, add `GreaterThan(0)`; if null is also invalid, keep `NotNull()` or `NotEmpty()` in front of it.
  • With FluentValidation, when would you call ValidateAndThrow instead of Validate?
    When the caller treats invalid input as exceptional and some outer layer already turns a `ValidationException` into a response, for example in a command handler. `ValidateAndThrow` is shorthand for `Validate` with the `ThrowOnFailures()` option, and the exception's `Errors` property carries the same `ValidationFailure` list. Where you branch on the outcome yourself, `Validate` and `IsValid` are cheaper and clearer.

  • NotNull and NotEmpty are the same check with different messages.
  • NotNull on an int property catches a quantity the client left out.
  • NotEmpty only rejects the empty string, so spaces still pass.
  • Validate throws an exception as soon as one rule fails.
  • FluentValidation rules are attributes placed on the command's properties.
open as a page

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%

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.

open as a page

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

level: middleimportance: should knowfreq 55%

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.

open as a page

With FluentValidation, an order validator with a MustAsync rule passes its TestValidate unit tests yet throws in production. Why, and how should it be tested?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The synchronous path throws only once execution reaches an async rule. Tests that stop earlier, at a failing cascade, a false When or a null child, never reach MustAsync, but a valid production order does. Call ValidateAsync everywhere and test with TestValidateAsync, including a valid case.

open as a page

In FluentValidation 12, what do Cascade(CascadeMode.Stop), RuleLevelCascadeMode and ClassLevelCascadeMode each stop, and what replaced StopOnFirstFailure?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Both levels default to Continue. Rule level, set by Cascade(CascadeMode.Stop) or RuleLevelCascadeMode, skips a chain's later validators after one fails. Class level, ClassLevelCascadeMode, ends the run after the first failing rule. FluentValidation 12 removed StopOnFirstFailure.

open as a page

When should a .NET team standardise on FluentValidation validator classes instead of DataAnnotations attributes, and which team rules should a lead set with it?

level: principalimportance: should knowfreq 35%

basics

~20 s

Adopt FluentValidation when rules are conditional, cross-field, asynchronous or must stay off the model, and when validators should be unit-tested alone. It costs a class per model and explicit invocation, so set rules: one validator per command, ValidateAsync, agreed cascade defaults.

open as a page