The recommendation for FluentValidation is to use manual validation:
On https://docs.fluentvalidation.net/en/latest/aspnet.html you can read that the automatic approach is deprecated:
We no longer recommend using this approach for new projects but it is still available for legacy implementations.
- It is harder to debug: The ‘magic’ nature of auto-validation makes it hard to debug/troubleshoot if something goes wrong as so much is done behind the scenes.
And the manual approach is recommended:
With manual validation, you inject the validator into your controller (or api endpoint), invoke the validator and act upon the result. This is the most straightforward approach and also the easiest to see what’s happening.
I totally agree that this way is cleaner and easier to understand.
But what about the built in model validation that happens before the manual validation with FluentValidation? If I implement a very complex validator with FluentValidation, it might happen that the built in validator already adds validation errors to the model state and the custom validator won't be triggered. The result is an incomplete validation of the model. But I prefer to completely validate the model, and prevent to return a different set of messages each time.
How can I prevent double validation like this? Should the built in validator be deactivated or is there another way to only use the FluentValidation validator except for the automatic approach?
FluentValidation has built-in extension
.AddToModelState(), so it's possible to add validation errors from fluent validator to errors from asp.net core validation. Example from their docs:Source: https://docs.fluentvalidation.net/en/latest/aspnet.html
Also you could "turn off" asp.net core validation, if you want: Correct way to disable model validation in ASP.Net Core 2 MVC