Search code examples
c#fluentvalidation

How to dynamically select a validator based on property's runtime type?


Given a base class that has a generic parameter which is used to define the type of a property and which has a restriction to another base type, when writing a Fluent Validator for a derived class how can this validator switch which child validator is applied to the generic property?

Here are some sample classes to demonstrate this configuration:

public abstract class BaseParent<TChildType> where TChildType : BaseChild
{
    public TChildType Child {get; set;}
}

public abtract class BaseChild
{
    public sting ChildPropOne {get; set;}
}

public class ChildA : BaseChild
{
    public string ChildAPropOne {get; set;}
}

public class ChildB: BaseChild
{
    public string ChildBPropOne {get; set;}
}

public class ParentA<TChildType> : BaseParent<TChildType> where TChildType : BaseChild
{
    public string ParentAPropOne {get; set;}
}

public class ParentB<TChildType> : BaseParent<TChildType> where TChildType : BaseChild
{
    public string ParentBPropOne {get; set;}
}

My current setup forces a different validator class for each parent type + child type combination. Ideally I can write one validator per parent and one per child and have the parent validator able to choose which child validator to call


Solution

  • You can inject child's validator instance into parent's validator and use SetValidator for Child property:

    public class ParentAValidator<TChildType> : AbstractValidator<ParentA<TChildType>> where TChildType : BaseChild
    {
        public ParentAValidator(IValidator<TChildType> childValidator)
        {
            RuleFor(p => p.Child).SetValidator(childValidator);
        }
    }