Clean model validation with FluentValidation in .NET
Model validation often starts as a guard against null values and malformed email addresses. That is useful, but it becomes difficult when the same checks are scattered through controllers, domain objects and background workers. Each placement creates a different error shape, and some paths quietly skip checks altogether. A clean approach gives validation one home while leaving business rules where they belong.
The need is familiar to Australian development teams. A SaaS product priced in AUD may serve customers in Sydney, Melbourne, Brisbane and Perth. Someone applying for a service from a train needs prompt feedback, and organisations handling personal information may be subject to the Privacy Act 1988 and Australian Privacy Principles. Validation should reject bad input without copying sensitive values into logs or telemetry.
FluentValidation is a strong fit for .NET because it turns validation into explicit, testable rule objects. A validator can express simple field checks, dependent conditions and asynchronous lookups without coupling those rules to a controller or an HTTP response. It also supports dependency injection, which matters when a rule needs a repository or another application service. The result is validation that can run in an API, a command handler or a scheduled process.
This article uses a small customer-creation request to show the full path: define an input model, create its validator, register it with the service container, invoke it at the boundary and return a consistent problem response. It also separates three concerns that are often blurred together: input validation, domain invariants and database constraints. Keeping those boundaries visible makes the code easier to test and gives every rule a clear reason to exist.
Keep validation at the right boundary
Validation should answer a specific question: is this input acceptable for this operation? It is not the only quality check in a .NET application. A request DTO describes data received from a client, while an entity or aggregate describes a valid business object. Mixing them makes every controller responsible for reconstructing an object that the domain should be capable of creating safely.
Keep the request model deliberately narrow. Include only values needed by the use case, use precise types where possible and avoid binding directly to persistence entities. In the example below, an API receives four strings, and the domain layer remains responsible for creating a customer. This prevents an over-posted JSON payload from changing fields the caller was never meant to control.
public sealed record CreateCustomerRequest(
string Email,
string MobileNumber,
string Postcode,
string State);
Domain validation has a different purpose. A domain invariant says the object must never exist in an invalid state, regardless of whether it came from HTTP, a message queue or a migration. FluentValidation can protect the operation boundary, but the domain constructor or factory should still reject impossible values. A database unique constraint then provides the final defence against races. When a rule fails, decide whether it is an input error, a domain conflict or an infrastructure failure instead of collapsing all three into false.
Build rules that explain themselves
Install the core package and the dependency-injection extensions in the project that owns the application rules:
dotnet add package FluentValidation
dotnet add package FluentValidation.DependencyInjectionExtensions
Then define a validator beside the request type. These rules fit Australian customer data, including four-digit postcodes and the standard state and territory codes:
using FluentValidation;
public sealed class CreateCustomerValidator
: AbstractValidator<CreateCustomerRequest>
{
private static readonly HashSet<string> AustralianStates =
new(StringComparer.OrdinalIgnoreCase)
{
"ACT", "NSW", "NT", "QLD",
"SA", "TAS", "VIC", "WA"
};
public CreateCustomerValidator()
{
RuleFor(x => x.Email)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.EmailAddress();
RuleFor(x => x.MobileNumber)
.NotEmpty()
.Matches(@"^(?:\+61|0)4\d{8}$")
.WithMessage("Enter a valid Australian mobile number.");
RuleFor(x => x.Postcode)
.Matches(@"^\d{4}$")
.WithMessage("Enter a four-digit Australian postcode.");
RuleFor(x => x.State)
.Must(state => AustralianStates.Contains(state))
.WithMessage("Choose a valid Australian state or territory.");
}
}
Each rule should have one clear job. Cascade(CascadeMode.Stop) prevents an empty email from producing several confusing errors, while WithMessage gives the client actionable text. The state check uses a case-insensitive set because abbreviations are data, not a reason to create duplicated constants elsewhere. If the business accepts international phone formats, replace the fixed pattern with a deliberate policy rather than loosening it accidentally.
Reuse common rules through extension methods, Include and child validators, and use RuleForEach for each item in a collection. Keep feature-specific validators small enough to scan. A validator that depends on a database or HTTP client should receive that dependency through its constructor; this preserves testability and lets the service container manage lifetimes.
Handle dependent and asynchronous checks
Some rules depend on another field. Compare the confirmation email with the original, or require a billing address only when the payment method needs one. FluentValidation keeps these relationships next to the relevant input rules:
RuleFor(x => x.ConfirmEmail)
.Equal(x => x.Email)
.WithMessage("Email addresses must match.");
Database-backed checks are also possible with MustAsync. Inject the repository into the validator and pass the request cancellation token through the query:
public sealed class AssignCustomerValidator
: AbstractValidator<AssignCustomerRequest>
{
private readonly ICustomerRepository _customers;
public AssignCustomerValidator(ICustomerRepository customers)
{
_customers = customers;
RuleFor(x => x.CustomerId)
.Cascade(CascadeMode.Stop)
.NotEmpty()
.MustAsync(async (id, cancellationToken) =>
await _customers.ExistsAsync(id, cancellationToken))
.WithMessage("The selected customer does not exist.");
}
}
An asynchronous existence check is useful, but it is not a concurrency guarantee. Another process can insert the same value immediately after the check succeeds. Keep a unique index on the database and translate the database conflict into a domain-level error if the operation must stay idempotent. Also distinguish a dependency timeout from a rule failure; validation errors should not conceal an unhealthy service.
Connect validation to ASP.NET Core
Register validators during application startup. The assembly scan finds validators and normally gives them a scoped lifetime, which suits validators that depend on scoped repositories:
builder.Services.AddValidatorsFromAssemblyContaining<CreateCustomerValidator>();
An explicit validation gate is predictable in minimal APIs and easy to locate in controller-based applications. Inject IValidator<T>, validate before calling application logic, and translate failures into ASP.NET Core’s ValidationProblemDetails shape:
app.MapPost("/customers", async (
CreateCustomerRequest request,
IValidator<CreateCustomerRequest> validator,
ICustomerService customers,
CancellationToken cancellationToken) =>
{
var result = await validator.ValidateAsync(request, cancellationToken);
if (!result.IsValid)
{
var errors = result.Errors
.GroupBy(failure => failure.PropertyName)
.ToDictionary(
group => group.Key,
group => group.Select(error => error.ErrorMessage).ToArray());
return Results.ValidationProblem(errors);
}
var customer = await customers.CreateAsync(request, cancellationToken);
return Results.Created($"/customers/{customer.Id}", customer);
});
The response status is 400 Bad Request, and field names match the request contract. This matters for clients that surface errors beside form fields, as well as for integration clients that need one stable machine-readable format. Keep internal exception messages out of the response; logs can carry correlation identifiers without adding the submitted values.
ASP.NET Core already rejects malformed JSON through model binding, while FluentValidation checks the deserialised values. Automatic MVC integration can coexist with explicit checks, but avoiding duplicate execution matters: a client should receive one list of errors, not the same failure reported twice. For APIs, the explicit gate also gives background endpoints and integration tests a consistent place to verify the boundary.
Turn validation into a repeatable practice
Treat validators as code with unit tests. Cover empty required values, valid values, invalid formats, dependent fields and the exact error messages exposed to clients. For asynchronous rules, replace the repository with a test double and verify both successful and failed lookups. Keep fixtures synthetic; real customer records do not belong in a test suite or a validation failure log.
The same boundary applies beyond HTTP. A worker responsible for scheduled Azure Batch jobs should validate each job payload at the start, then treat a malformed record as a controlled failure rather than passing it deeper into the pipeline. A message consumer can use the same validator, which keeps the definition of valid input consistent across web and batch entry points.
Choose one endpoint or message consumer today. Add its request model and validator, register the validator, return the standard problem response and write three focused tests: one empty value, one malformed value and one valid value. Once that path is working, reuse the pattern for each new operation and keep validation decisions visible in code review.