FluentValidation.AspNetCore 引入包
public class Login2RequestValidator : AbstractValidator<Login2Request>
{
public Login2RequestValidator()
{
RuleFor(x => x.Email).NotNull().EmailAddress()
.Must(v => v.EndsWith("@qq.com") || v.EndsWith("@163.com"))
.WithMessage("只支持QQ和163邮箱");
RuleFor(x => x.Password).NotNull().Length(3, 10)
.WithMessage("密码长度必须介于3到10之间")
.Equal(x => x.Password2).WithMessage("两次密码必须一致");
}
}
实体 :
注意 record 是C# 10 新语法 微软文档:https://docs.microsoft.com/zh-cn/dotnet/csharp/whats-new/csharp-10#record-structs 其他介绍:https://blog.51cto.com/ggwhsd/4961787
public record Login2Request(string Email, string Password, string Password2);
注入 AddFluentValidation
builder.Services.AddFluentValidation(fv => {
Assembly assembly = Assembly.GetExecutingAssembly(); // 注入程序集
fv.RegisterValidatorsFromAssembly(assembly);
});