Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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


1 Answers

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);
    }
}
like image 110
Aleksey L. Avatar answered Nov 30 '25 07:11

Aleksey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!