skip to content

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%

answer

  1. rules beside the model or apart
  2. conditions, cross-field, async lookups
  3. nothing runs unless you call it
  4. one validator per command, one invocation style

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.

solid answer

~50 s

Attributes are fine for simple, static constraints on models the team owns. FluentValidation earns its cost when rules depend on other fields or on state, need an async lookup, differ per command, or must stay off a type you cannot or should not annotate, and when you want each validator tested alone with `TestValidate`. The cost is a second class per model, a dependency to upgrade (version 12 requires .NET 8), and the fact that nothing runs unless you invoke it; FluentValidation itself no longer recommends its automatic MVC integration, so the invocation point is a deliberate decision. The rules I would set: one validator per command rather than rule sets for create versus update; always `ValidateAsync`; a global `DefaultRuleLevelCascadeMode = CascadeMode.Stop`; stable `WithErrorCode` values for clients; one validation style per model; and a test suite per validator that includes a valid case.

go deeper

for a junior

Recall the difference: attributes sit on the model's properties, while FluentValidation puts the rules in a separate validator class built from RuleFor chains.

for a middle

Explain which rule shapes favour FluentValidation, such as conditional, cross-field, async and per-command rules, and what explicit invocation means for a codebase.

for a senior

Weigh concrete costs: a second class per model, async discipline, rule-set pitfalls, and the version 12 requirement of .NET 8, against testability and expressiveness.

for a principal

Own the policy: one validation style per type, one validator per command, ValidateAsync everywhere, a global cascade default, stable error codes, and a staged migration that deletes attributes as it goes.

Choosing between **DataAnnotations** (attributes such as `[Required]` and `[StringLength]` placed on a model's properties) and **FluentValidation** (a library where each model gets a separate validator class built from `RuleFor` chains) is less a question of which is better than of which costs the team less over years. A lead's job is to make the choice explicit and attach rules to it so the codebase does not end up with both, half-applied. ## What FluentValidation buys - **Rules live outside the model.** Commands can be plain records or types from another assembly; the validator is a separate class that can take constructor dependencies. - **Conditional and cross-field rules read naturally.** `When`, `Unless`, `Otherwise`, comparison validators taking a lambda, and `Must` with the root object express "express delivery needs a phone" or "discount at most the subtotal" without a custom attribute per rule. - **Asynchronous rules.** `MustAsync` and `CustomAsync` can await a lookup, with a cancellation token. - **Collections and nested objects.** `RuleForEach` and child validators produce indexed failure paths such as `LineItems[1].Quantity`. - **Testability.** `TestValidate` and `TestValidateAsync` assert on a validator in isolation, with fakes for its dependencies. - **Per-use-case rules.** A create-order and an amend-order command can have different validators over similar data, instead of one set of attributes that must suit every use. ## What it costs | Cost | Why it matters | |---|---| | A second class per model | rules and shape now live in two files; reviewers must open both | | Explicit invocation | nothing validates unless code calls the validator; the wiring is covered in the ASP.NET Core material | | Async discipline | a validator with async rules throws if a synchronous `Validate` reaches them | | No client-side hints | FluentValidation is a server-side library; attributes feed client-side validation hints, and the separate package that exposed validator metadata for that is no longer supported | | A dependency to upgrade | version 12 requires .NET 8 and removed APIs deprecated in 11 | FluentValidation's own documentation **no longer recommends** its automatic integration with the ASP.NET Core MVC validation pipeline for new projects, partly because that pipeline is synchronous and cannot run async rules. So adopting the library also means deciding where validators are invoked, rather than expecting them to fire on their own. ## When the decision tips Lean to **attributes** when models are simple data transfer types with static constraints, the team mainly builds server-rendered forms that rely on attribute-driven client-side hints, and validation rarely changes. Lean to **FluentValidation** when: 1. a meaningful share of rules are conditional, cross-field or need lookups; 2. the same data is validated differently per command; 3. the team wants validation unit-tested as its own layer; 4. models are records or shared types the team prefers not to decorate. A mixed codebase is acceptable at a **boundary** level, for example attributes on view models and validators on commands, but never on the same type: two sources of truth for one model drift apart and can report the same field twice. ## Team rules that make it work 1. **One validator per request or command type.** Prefer separate validators over rule sets for variants such as create versus update. Rule sets are easy to misuse: a plain `Validate` runs only rules outside any rule set, and a child validator attached with `SetValidator` inherits the parent's rule-set selection. 2. **Always `ValidateAsync`.** Even for validators that are synchronous today, so adding a `MustAsync` later cannot break a synchronous caller. 3. **One cascade default, set once.** For example `ValidatorOptions.Global.DefaultRuleLevelCascadeMode = CascadeMode.Stop`, leaving class level at `Continue`, so each field reports one message and every bad field is reported. 4. **Stable error codes.** Use `WithErrorCode` for anything a client branches on; messages are for humans and get reworded or localised. 5. **Boundary checks only.** Validators check request shape and simple business preconditions; domain invariants stay in the domain model, even when a lookup in a validator is tempting. 6. **Tests per validator.** A valid case, a failing case per rule, and `TestValidateAsync` wherever an async rule exists. ## Migration and version notes Version 12 is mainly a clean-up release, which its upgrade guide describes as having no new features: it drops platforms older than .NET 8, removes the `Transform` methods (the documentation suggests computed properties on the model instead), removes `CascadeMode.StopOnFirstFailure`, and removes the option to disable the root-model null check. A team migrating from attributes should move one bounded area at a time, delete the attributes from each migrated model in the same change, and keep both styles from validating any single type.

  • With FluentValidation, why might a lead ban rule sets for create versus update variants of a command?
    Because rule-set selection is easy to get wrong silently: a plain `Validate` runs only rules outside any rule set, so a forgotten `IncludeRuleSets` skips rules with no error, and child validators inherit the parent's selection. Separate validators per command make the variant explicit in the type system and in tests, at the cost of some repeated rules, which can be shared through extension methods or a common child validator.
  • With FluentValidation, where should a uniqueness check such as 'order reference not already used' live?
    A `MustAsync` rule gives a fast, friendly failure for the common case, but it is a check-then-act race: two requests can both pass before either commits. The guarantee has to come from the data store or the domain, for example a unique constraint. Treat the validator rule as a usability layer on top, never as the invariant itself.

  • FluentValidation validators run automatically once the package is referenced.
  • Using both attributes and a validator on the same model gives double protection.
  • Rule sets are the cleanest way to share one validator between create and update.
  • A MustAsync uniqueness rule guarantees no duplicate order references can be stored.
  • Calling synchronous Validate is safe for good once today's validators have no async rules.

Assumes FluentValidation 12, which requires .NET 8, removed the APIs deprecated in 11, and whose documentation no longer recommends the automatic MVC pipeline integration.