使用asp.net core默认的属性

    public class LoginRequest
    {
        [MinLength(3)]
        public string Username { get; set; }

        [Required]
        public string Email { get; set; }

        [MinLength(5)]
        public string Password { get; set; }

        [Compare(nameof(Password))]
        public string Password2 { get; set; }
    }

在login调用之前,会触发数据校验

使用FluentValidation.AspNetCore

    <PackageReference Include="FluentValidation.AspNetCore" Version="10.3.6" />

注入

builder.Services.AddFluentValidation(config =>
{
    config.RegisterValidatorsFromAssembly(Assembly.GetExecutingAssembly());
});
    public class CustomerValidator : AbstractValidator<LoginRequest>
    {
        public CustomerValidator(UserManager<MyUser> userManager)
        {
            RuleFor(x => x.Username).MinimumLength(3)
                .MustAsync(async (x, _) => await userManager.FindByNameAsync(x) == null)
                .WithMessage(x => $"user {x.Username} already exists");
            RuleFor(x => x.Email).NotEmpty().EmailAddress().WithMessage("email is not valid")
                .Must(v => v.EndsWith("@qq.com")).WithMessage("only support email from qq.com");
            RuleFor(x => x.Password)
                .Length(6, 10).WithMessage("password length must between 6 and 10 chars")
                .Equal(x => x.Password2)
                .WithMessage(x => $"password {x.Password} must be identical as password2 {x.Password2}");
        }
    }