What is the difference between Data Annotations validation and FluentValidation?
Quick Answer
Data Annotations ([Required], [Range]) are attributes on the model — simple, built-in, run automatically. FluentValidation is a separate library where rules live in a Validator<T> class — better for complex, conditional, cross-field, or async (DB-checking) rules, and it keeps validation out of the model.
Data Annotations are the attribute approach — [Required], [StringLength] right on the model, and the framework runs them for you. They're fine for simple shape validation but they can't do “this is required only when that other field has a certain value” cleanly, and they can't inject a service to check the database. FluentValidation puts the rules in a dedicated validator class with a fluent API, it's a DI service so it can do async database checks, and it keeps the model clean. I'll often use annotations for the trivial stuff and FluentValidation for the real business rules.
- Data Annotations: great for straightforward rules; awkward for “field B is required only if field A is X”, and you can't inject services (no DB lookups).
- FluentValidation:
RuleFor(x => x.Email).NotEmpty().EmailAddress().MustAsync(BeUniqueEmail); the validator is a DI service so it can call a repository. - Wire it up so ASP.NET Core runs it automatically and populates
ModelState(or injectIValidator<T>and call it in a filter/handler). - Many teams use both — annotations for trivial shape rules, FluentValidation for business rules.