25

I used Fluent Validator. But sometimes I need create a hierarchy of rules. For example:

[Validator(typeof(UserValidation))]
public class UserViewModel
{
    public string FirstName;
    public string LastName;
}

public class UserValidation : AbstractValidator<UserViewModel>
{
    public UserValidation()
    {
        this.RuleFor(x => x.FirstName).NotNull();
        this.RuleFor(x => x.FirstName).NotEmpty();

        this.RuleFor(x => x.LastName).NotNull();
        this.RuleFor(x => x.LastName).NotEmpty();
    }
}

public class RootViewModel : UserViewModel
{
    public string MiddleName;       
}

I want to inherit validation rules from UserValidation to RootValidation. But this code didn't work:

public class RootViewModelValidation:UserValidation<RootViewModel>
{
    public RootViewModelValidation()
    {
        this.RuleFor(x => x.MiddleName).NotNull();
        this.RuleFor(x => x.MiddleName).NotEmpty();
    }
}

How can I inherit validation class using FluentValidation?

krillgar
  • 12,596
  • 6
  • 50
  • 86
Ivan Korytin
  • 1,832
  • 1
  • 27
  • 41

1 Answers1

36

To resolve this, you must change UserValidation class to generic. See code below.

public class UserValidation<T> : AbstractValidator<T> where T : UserViewModel
{
    public UserValidation()
    {
        this.RuleFor(x => x.FirstName).NotNull();
        this.RuleFor(x => x.FirstName).NotEmpty();

        this.RuleFor(x => x.LastName).NotNull();
        this.RuleFor(x => x.LastName).NotEmpty();
    }
}

[Validator(typeof(UserValidation<UserViewModel>))]
public class UserViewModel
{
    public string FirstName;
    public string LastName;
}

public class RootViewModelValidation : UserValidation<RootViewModel>
{
    public RootViewModelValidation()
    {
        this.RuleFor(x => x.MiddleName).NotNull();
        this.RuleFor(x => x.MiddleName).NotEmpty();
    }
}

[Validator(typeof(RootViewModelValidation))]
public class RootViewModel : UserViewModel
{
    public string MiddleName;
}
Justin Pavatte
  • 1,198
  • 2
  • 12
  • 18
Ermak
  • 384
  • 3
  • 3