流浪のwolf

卷帝

导航

第三方的开源库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}不存在");
    }
}

 

posted on 2023-11-05 19:14  流浪のwolf  阅读(21)  评论(0编辑  收藏  举报