Search code examples
c#asp.net-corefluentvalidation

C# - FluentValidation(11.4.0) - Generic type validation


I have a FluentValidation class:

public class ResourceDtoValidator<TResource> : AbstractValidator<ResourceDtoValidator<TResource>>

The problem is the next:

RuleFor(x => x.Resource)

I have a TResource property in ResourceDtoValidator ( x.Resource is that prop ) which can be 3 different type. Forexample: HumanResource, HardwareResource, OtherResource.

How can i set a rule for that?

Thanks for helping.

I tried to write an extension method, but it was very ugly and not worked :(


Solution

  • To set a validation rule for the Resource property, you can make use of the When method provided by FluentValidation which allows you to conditionally apply a validation rule based on the value of another property like so:

    public class ResourceDtoValidator<TResource> : AbstractValidator<ResourceDtoValidator<TResource>>
    {
        public ResourceDtoValidator()
        {
            RuleFor(x => x.Resource)
                .When(x => x.Resource is HumanResource, () => 
                {
                    // Set validation rules for HumanResource type
                })
                .When(x => x.Resource is HardwareResource, () => 
                {
                    // Set validation rules for HardwareResource type
                })
                .When(x => x.Resource is OtherResource, () => 
                {
                    // Set validation rules for OtherResource type
                });
        }
    }
    

    In each of the When methods, you can set the validation rules specific to each type of Resource using the FluentValidation API.