第三方的开源库FluentVaidation校验字段的
内置的 using System.ComponentModel.DataAnnotations;
基本使用:
1. 安装包
FluentValidation.AspNetCOre
2. 注册服务
builder.Services.AddFluentValidation(fv => { Assembly assembly = Assembly.GetExecutingAssembly(); fv.RegisterValidatorsFromAssembly(assembly); });
具体规则
using FluentValidation; using FluentValidation中注入服务.Controllers; public class Login3RequestValidator : AbstractValidator<Login3Request> { public Login3RequestValidator(TestDbContext dbCtx) { RuleFor(x => x.UserName).NotNull() .Must(name => dbCtx.Users.Any(u => u.UserName == name)) .WithMessage(c => $"用户名{c.UserName}不存在"); } }