Search code examples
c#.netblazorfluentvalidationfluentvalidation-2.0

How to write a validator class using fluent validation for a class inheriting from a concrete class?


I am slightly confused regarding the example mentioned on the fluent validation documentation regarding inheritance. https://docs.fluentvalidation.net/en/latest/inheritance.html#

How do I implement fluent validation when I inherit from a concrete class though? The example mentioned is the official documentation is more along the lines of interface implementation as I understand.

Lets say I have a base class:

public class Base
{
  public string A;
  public string B;
}

public class New : Base
{
  public string C;
  public string D;
}

I have now gone ahead and written a validator for Base. When I write the validator for New how do I include properties from the base too or is there a certain amount of magic happening all by itself?


Solution

  • The inheritance docs you link pertain to using a separate validator on a property, what you are looking for is using the Include() function linked below. It allows you to use validators for parent classes/interfaces as shown in the docs and related post below.

    Example from other post + docs:

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

    Assuming a validator is written for the base class, we can add its rules to a validator for the derived like so:

    public class Derived1Validator : AbstractValidator<Derived1>
    {
        public Derived1Validator()
        {
            Include(new BaseValidator());
            RuleFor(d => d.Derived1Name).NotNull();    
        }
    }
    
    public class Derived2Validator : AbstractValidator<Derived2>
    {
        public Derived2Validator()
        {
            Include(new Derived1Validator());
            RuleFor(d => d.Derived2Name).NotNull();
        }
    }
    

    https://docs.fluentvalidation.net/en/latest/including-rules.html?highlight=Include#including-rules

    C# FluentValidation for a hierarchy of classes