Home > Software engineering >  How to create a base FluentValidation
How to create a base FluentValidation

Time:02-04

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?

CodePudding user response:

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

CodePudding user response:

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.

  •  Tags:  
  • Related