流利的验证。为所有模型添加验证器服务

FluentValidator. Add _validateService for all models

我需要创建流畅的 _validator,我不会只使用一个模型。如果我的控制器需要更多模型?我将为每个模型创建 _validator{modelName}?

我的代码

public class UserDtoValidator : AbstractValidator<UserDTO>
{
    public UserDtoValidator()
    {
        RuleFor(p => p.Email).NotEmpty().EmailAddress()
            .WithMessage("{PropertyName} should be not empty.");
        RuleFor(p => p.Password).NotNull().Length(5, 30)
            .WithMessage("{PropertyName} should be not empty.");
        RuleFor(p => p.PasswordConfirm).Equal(p => p.Password);
    }
}

Controller.cs

 private readonly IValidator<UserDTO> _validator;

    public UserController(IValidator<UserDTO> validator)
    {
        _validator = validator;
    }

HttpPost

 var validResult = _validator.Validate(model);
 if (validResult.IsValid)
 {

 }
 

启动

 services.AddControllers().AddFluentValidation();
 services.AddSingleton<IValidator<UserDTO>, UserDtoValidator>();

做工不错。但是我的 _validator 中需要多个模型。

我认为使流畅的验证器通用没有多大意义,因为所有模型可能具有不同的属性并且需要不同的验证来验证属性。

除非你的这些模型继承了共同的class,否则你可以使用BaseValidator来共享一个验证器方法。

 public class Teacher 
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
    }
    public class UserDTO  
    {
        public string Email { get; set; }
        public string Password { get; set; }
        public string PasswordConfirm { get; set; }
    }
   public class BaseValidator<T> : AbstractValidator<T> 
    {
        public BaseValidator()
        {
        }
    }

    public class TeacherValidator : BaseValidator<Teacher>
    {
        public TeacherValidator()
        {
            RuleFor(p => p.Name).NotEmpty().WithMessage("{PropertyName} should be not empty.");
            RuleFor(p => p.Age).InclusiveBetween(18, 60)
                .WithMessage("{PropertyName} should between 18-60.");
            RuleFor(p => p.Gender).Must(x => new string[] { "Male", "Female" }.Contains(x)).WithMessage("Then gender can only be male or female");
        }
    }
    public class UserDtoValidator : BaseValidator<UserDTO>
    {
        public UserDtoValidator()
        {
            RuleFor(p => p.Email).NotEmpty().EmailAddress()
                .WithMessage("{PropertyName} should be not empty.");
            RuleFor(p => p.Password).NotNull().Length(5, 30)
                .WithMessage("{PropertyName} should be not empty.");
            RuleFor(p => p.PasswordConfirm).Equal(p => p.Password);
        }
    }

或者您可以查看