The .NET realization of validation with FluentValidation, for anything that gets validated (the two-level model's principles are in `ddd`). Use when writing or reviewing FluentValidation validators — for a request, a query criterion, a value object or an aggregate —, when deciding where a rule lives (type invariant vs use-case precondition), wiring validators into DI or assembling them without a container, raising the typed ValidationException, or mapping validation failures to ProblemDetails...
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Validation Dotnet?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/jorgecostamacia-validation-dotnet-code-harness)
---
name: validation-dotnet
description: >-
The .NET realization of validation with FluentValidation, for anything that
gets validated (the two-level model's principles are in `ddd`). Use when
writing or reviewing FluentValidation validators — for a request, a query
criterion, a value object or an aggregate —, when deciding where a rule
lives (type invariant vs use-case precondition), wiring validators into DI
or assembling them without a container, raising the typed
ValidationException, or mapping validation failures to ProblemDetails. It
encodes: one validator and one exception per validated thing, per-call
validators from DI or static Create() chains, composition with
Include/SetValidator, every rule evaluated (no Cascade), the rule and
message conventions, input from outside the service always validated for
shape and size, and level-2 preconditions in Application with DI.
---
# Validation in .NET (FluentValidation)
The .NET *how* of the two-level model defined in `ddd` (load it for the *why*). **FluentValidation is the accepted core coupling** for validation. The choice is deliberate and evaluated: do not wrap it and do not replace it. This skill covers validators for anything: a request, a query criterion, a domain type. `ddd-dotnet` says how a domain model applies them: which validator each type builds, and when.
**The libraries:** the shared `ValidationException` base and the base validators come from the DDD library, `JorgeCostaMacia.DDD.*` in this family ([its docs](https://github.com/JorgeCostaMacia/ddd-dotnet/tree/main/docs) list what each base validator checks). Its HTTP rendering is `JorgeCostaMacia.Http.ProblemDetails`'s, in [http-dotnet](https://github.com/JorgeCostaMacia/http-dotnet). How they work inside is their docs'; this skill is how the code validates.
## The two levels, realized
| Level | Question | Lives in | DI |
| --- | --- | --- | --- |
| **1 — Invariants** | "Is this object correct in itself?" | The type: its validator, invoked by its `Create` | **Never** — type rules are pure (no services) |
| **2 — Preconditions** | "Is this correct object admissible *here, now*?" | The use case (Application): checks with injected dependencies | **Always** — that's what marks a rule as level 2 |
Litmus test: **if the rule needs a service, it's level 2.** (Format, ranges, cross-field coherence → the type. Uniqueness, referenced-thing-exists, state conflicts → Application.)
## One validator and one exception per validated thing
Each validated thing has **its own validator** (`<X>Validator`), which holds all its rules, and **its own exception** (`<X>ValidationException`), which the validator raises. This applies to a value object, an aggregate, an entity, a request and a query criterion. Nothing validates through a generic validator, and nothing throws a generic exception.
## The validator pattern
```csharp
internal sealed class FacturaValidator : AbstractValidator<Factura>
{
// The ONLY constructor: receives its composition — usable via DI when needed.
public FacturaValidator(IValidator<FacturaEmail> email)
{
RuleFor(v => v.Email) // a part: its own validator's rules
.SetValidator(email);
RuleFor(v => v.Total) // this validator's own rule
.GreaterThanOrEqualTo(0);
}
// The self-contained assembly: chains the OTHER validators' Create() —
// never `new`s another validator (its chain is its own knowledge).
public static FacturaValidator Create() => new FacturaValidator(FacturaEmailValidator.Create());
// Failures raise the thing's OWN exception, never a generic one.
protected override void RaiseValidationException(
ValidationContext<Factura> context,
ValidationResult result)
=> throw new FacturaValidationException(result.Errors);
}
```
- **Two ways to obtain a validator, one shape.** Where a container exists, resolve the validator from DI, the standard FluentValidation way (requests, query criteria; see *Boundary*). **Where there is no container**, such as inside a static factory, assemble it with `XValidator.Create()`: the chain builds itself and needs no injection. The constructor takes its ingredients, and this lets the same validator serve both ways.
- **Ctor receives ingredients; `Create` fabricates complete.** A validator with nothing to compose keeps a parameterless ctor and a trivial `Create() => new XValidator();`.
- **`RaiseValidationException` is not optional.** Without the override, FluentValidation throws its own `ValidationException`. That exception is *not* the domain's shared base, which is the one a bus retry policy excludes. So a malformed message would climb the whole retry ladder, and the bus would not park it.
- **Compose, don't repeat**: `SetValidator` brings a part's rules under its property (an optional part adds `.When(v => v.Part is not null)`). `Include` brings a validator hierarchy's rules onto the same object, such as a derived type that includes its base's. The documentation only promises `Include` for the same type. Across the hierarchy, it works through `IValidator<in T>`'s contravariance, and the suites pin it. Cross-field rules are the composing validator's own.
- One `ValidateAndThrow` reports **every** failure with its property path (`Email.Value`, `Total`) in one exception — the full report `ddd` asks for. The pattern recurses through any depth of parts.
- **Per-call, no caching**: each validation builds a new validator (`XValidator.Create().ValidateAndThrow(x)`). Construction costs a few gen0 allocations, because FluentValidation caches compiled accessors globally. So a cached static instance is at most a later optimization, and only when a profiler shows the need. Never cache a validator with a bound on "now". The validator evaluates that bound when its constructor runs, and a cached one would freeze it at process start.
- Lambda style: **`v =>`** (nested scopes `v2`), not `value =>`. Explicit types throughout: `new XValidator(...)`, never `new(...)`.
- No `new` modifier on a validator's `Create` (validators don't inherit each other; they `Include`).
## Writing the rules
- **No `Cascade(CascadeMode.Stop)`.** Every rule runs, so an empty value may report two failures (`NotEmpty` and the `Must`) — accepted. Other validators can include a validator, so it must not decide how a chain it is part of stops.
- **A base validator rejects only what is not the type — and most check nothing at all.** A string base accepts an empty string, a number base any number. The library's docs list what each base checks. A policy (not empty, a range, a closed list) lives in the validator of the thing that has it. Never assume it from the base.
- **Bounds are literals in the rule**, never a public constant to clamp against, and two tests either side pin them.
- **Messages**: a custom check names its rule and says what it expected:
```csharp
RuleFor(v => v.Value)
.Must(v => MailAddress.TryCreate(v, out MailAddress? address) && address.Address == v)
.WithErrorCode("EmailValidator")
.WithMessage("{PropertyName} must be an email");
```
A closed list needs no code: `.Must(_types.Contains).WithMessage("{PropertyName} must be one of " + string.Join(", ", _types))`. Built-in rules (`NotEmpty`, `LessThan`…) keep FluentValidation's own messages.
## The ValidationException
`<X>ValidationException` derives the shared base, `ValidationException`, or the one its base type already extends (`DateTimeValueObjectValidationException`…). It carries a **fixed GUID code** and the failure list (`ImmutableList<ValidationFailure>`). The code is a UUIDv7 minted for that type and never copied; `ddd-dotnet` has the rule and names the test that guards it. At an HTTP boundary that list becomes per-field ProblemDetails errors (`JorgeCostaMacia.Http.ProblemDetails` renders it). The rest of a domain's exceptions (`NotFound`, `Exist`) belong to `ddd-dotnet`.
## Boundary — standard FluentValidation, when there is one
When a boundary validates its input (an HTTP request, a query criterion), its validator runs **first** in the handler (`validator.ValidateAndThrow(request)`). The caller then gets the complete per-field report in one response. It speaks the framework's idiom: constructor injection, normal DI registration (`AddScoped<IValidator<XRequest>, XRequestValidator>()`), the container composes the graph. Same shape as everything else: `<X>Request` + `<X>RequestValidator` + `<X>RequestValidationException`.
**Input from outside the service's own boundary is always validated** for shape and size: a public endpoint, a webhook, a partner's call. Every string gets a maximum length there, because the string base validator checks none. A public webhook also authenticates its sender (a signature or a token) before it reads the content.
A boundary validator is **optional only between the service's own internal services**. There, if the layer that owns the content validates it once, a boundary that only passes data on may validate only what its own infrastructure needs. Deserialization rejects a missing key only where the host turns on `RespectRequiredConstructorParameters`, which is off by default: an HTTP host sets it to `true` in `ConfigureHttpJsonOptions`. A message deserializer that leaves it off gives a missing key its default value. Don't add a request validator that duplicates a rule another layer owns.
## Level 2 — preconditions in Application
```csharp
// In the use-case service — dependencies injected, rejects with the family's domain error:
Factura? existing = await _context.FacturaRepository.FindAsync(aggregate.Id);
if (existing is not null)
{
throw new FacturaExistException(...);
}
```
- Level-2 checks stay **in the use case**, usually next to the load or insert they guard. A "validator with a repository inside" doubles the query and blurs the vocabulary. The warning sign is a validator constructor that asks for a repository. If the same check repeats across use cases, extract a helper or domain service — not a FluentValidation validator.
- Uniqueness gets the **double defense**: the application check gives the friendly domain error; the **unique index** in the schema scripts gives the concurrency-proof guarantee (`efcore-postgres-dotnet` says which indexes exist). What its violation becomes depends on the write. If the write is idempotent (see `messaging`), a duplicate key is a race between two writers: let it propagate, and the retry resolves it. If it is not idempotent, the duplicate is a business fact: translate it to the family's `<X>ExistException`. At an HTTP boundary, that is a 409. In a consumer, it is an exception that its retry policy excludes, since a repeat of the write cannot change the answer.
## Testing this model
- Per rule, its **red case**: `Create_OnInvalidX_ThrowsFamilyValidationException`.
- A bound from both sides: the last accepted value and the first rejected one.
- One `ValidateAndThrow` reports ALL failing rules — assert the failure list, not just the throw.
- A test helper never caches a validator either: the time bounds would freeze with it.