Reputation: 89
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 :(
Upvotes: 0
Views: 276
Reputation: 89
Actually i find a better way. I defined a common Interface for Resources and i used
RuleFor(x => x.Resource)
.SetInheritanceValidator(v =>
{
v.Add<HumanResource>(new HumanResourceValidator());
v.Add<HardwareResource>(new HardwareResourceValidator());
v.Add<OtherResourc>(new OtherResourcValidator());
});
Upvotes: 0
Reputation: 101
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.
Upvotes: 2