It depends on where you want to use your validators:
In the common scenario, where we have an application with N layers,
in the ASP.net layer, for the validation of View Models
, DTOs
or Commands
(e.g. to achieve fail-fast validation), just enable ImplicitlyValidateChildProperties
, as @StevenYates said:
services.AddMvc().AddFluentValidation(fv =>
{
fv.ImplicitlyValidateChildProperties = true;
});
When this is enabled, instead of having to specify child validators using SetValidator
, MVC’s validation infrastructure will recursively attempt to automatically find validators for each property automatically.
IMHO, this is great, because besides being practical, it prevents us from forgetting some .SetValidator (...)
!
Note that if you enable this behaviour you should not use SetValidator
for child properties, or the validator will be executed twice.
Doc: https://docs.fluentvalidation.net/en/latest/aspnet.html#implicit-vs-explicit-child-property-validation
But, in addition (or instead) of that, if you want to use FluentValidation in other layers (e.g. Domain), you need to use the SetValidator(...)
method, as @t138 said, for example:
RuleFor(customer => customer.Address).SetValidator(new AddressValidator());
Doc: https://docs.fluentvalidation.net/en/latest/start.html#complex-properties