-1
namespace Test
{

    public class A
    {
        public string Name { get; set; }
    }    
    public class AValidator : AbstractValidator<A>
    {
        public AValidator()
        {
            RuleFor(t => t.Name)
                .NotEmpty()
                .MinimumLength(10)
                .MaximumLength(20);
        }
    }

    public class B
    {
        public string Name { get; set; }
    }    
    public class BValidator : AbstractValidator<B>
    {
        public BValidator()
        {
            RuleFor(t => t.Name)
                .NotEmpty()
                .MinimumLength(10)
                .MaximumLength(20);
        }
    }
}

tried to create a common like this:

namespace Test2
{
    public interface IPerson
    {
        public string Name { get; set; }
    }

    public abstract class CommonABValidators<T> : 
                           AbstractValidator<T> where T : IPerson
    {
        protected CommonABValidators()
        {
            RuleFor(x => x.Name).NotNull();
        }
    }
}

but by calling

public class AValidator : CommonABValidators<A>

It should be convertible to IPerson, but in my case I have diffeent props in A that are not convertible to IPerson

Any Idea how to extract common params into common Validator?

Alex
  • 8,908
  • 28
  • 103
  • 157

2 Answers2

1

What you've done looks correct. Just make sure that your class A implements the IPerson interface and the validator will start working.

Tony Troeff
  • 338
  • 4
  • 19
0

Another option that you can try at least is to Include rules. Here you can find the official documentation: https://docs.fluentvalidation.net/en/latest/including-rules.html

All you need is to call Include(new CommonValidator()); and the common rules will be automatically included without inheriting a common base type.

Tony Troeff
  • 338
  • 4
  • 19