C# FluentValidation for a hierarchy of classes

Nikolay Nahimov picture Nikolay Nahimov · Jun 9, 2015 · Viewed 17.2k times · Source

I have a hierarchy of data classes

public class Base
{
    // Fields to be validated
}

public class Derived1 : Base
{
    // More fields to be validated
}

public class Derived2 : Base
{
    // More fields to be validated
}

What would be the appropriate way to validated Derived1 and Derived2 using FluentValidation framework without duplicating rules for fields of Base class?

Answer

Mohsin Syed picture Mohsin Syed · Mar 15, 2016
public class Derived2Validator : AbstractValidator<Derived2>
{
    public Derived2Validator()
    {
        Include(new BaseValidator());
        Include(new Derived1Validator());
        RuleFor(d => d.Derived1Name).NotNull();
    }
}

Derived2Validator does not need to inherit BaseValidator or Derived1Validator.

Use the Include method to include the rules from other validators.