With FluentValidation, how do you write a validator for a create-order command, and how do NotNull and NotEmpty differ?
answer
- a class per model, not attributes
- rules declared in the constructor
- a result object, not an exception
- null versus blank, empty or default
basics
~10 sInherit 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 sI 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 linesusing 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
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.
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.
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.
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.