FluentValidation学习 (.NET 6.0)

官方文档:FluentValidation — FluentValidation documentationhttps://docs.fluentvalidation.net/en/latest/index.html

安装

CLI:

dotnet add package FluentValidation

 NuGet 包管理器

Install-Package FluentValidation

Install-Package FluentValidation.AspNetCore
dotnet add package FluentValidation.AspNetCore

 

 链接规则写法

using FluentValidation;

   public class XXXValidator : AbstractValidator<Req_XXXDto>
    {
        public XXXValidator()
        {
            
            RuleFor(x => x.usename).MaximumLength(100);
        }

    }

FluentValidation支持通过 WithName 方法来指定属性别名 

using FluentValidation;
using FluentValidation.AspNetCore;
using WebApplication2.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddMvcCore().SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2)
    .AddFluentValidation(fu =>
    {
        fu.RunDefaultMvcValidationAfterFluentValidationExecutes=false;
        fu.RegisterValidatorsFromAssemblyContaining<CustomerValidation>();
    });
builder.Services.AddTransient<IValidator<Customer>, CustomerValidation>();
var app = builder.Build();


// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();
using FluentValidation;

namespace WebApplication2.Models
{
    public class Customer
    {
        public int Id { get; set; }

        /// <summary>
        /// 里斯
        /// </summary>
        public string Surname { get; set; }

        public string Forename { get; set; }

        public decimal Discount { get; set; }

        public string Address { get; set; }
    }
    public class CustomerValidation : AbstractValidator<Customer>

    {

        public CustomerValidation()

        {
            RuleFor(customer => customer.Surname)
                .NotEmpty()
                .WithName("张三")
                .WithMessage(ErrorMessage.NullData);
        }

        public class ErrorMessage
        {
            public static string NullData = "{PropertyName}不能为空";
            public static string RangeData = "{PropertyName}超出范围";
          
        }

    }
}
        public IActionResult Index(Customer customer)
        {
            if (!ModelState.IsValid)
            {

                CustomerValidation validator = new CustomerValidation();
                customer.Surname=string.Empty;
                validator.ValidateAndThrow(customer);
            }
            return View();
        }

自定义消息占位符

FluentValidation 默认支持多个消息占位符,包括{PropertyName}{PropertyValue}

    public static class SysOtherConstTip
    {
        #region 通用提示信息
        public const string Error = "第三方接口访问失败,请联系管理员!";

        public const string NeedLogin = "请先登录";

        public const string NoData = "未查询到数据";

        #endregion

        #region 业务模块提示信息

        #region XX通用提示信息
        public const string NullData = "{PropertyName}不能为空";
        public const string OutOfRange = "{PropertyName}超出范围";

        #endregion
        /// ...
        #endregion
    }

默认情况,编写多个链式验证规则时,无论前一个规则失败与否,后一个规则都将执行 。

FluentValidation 9.1 

使用 CascadeMode.Stop

 RuleFor(x => x.zt)
                .Cascade(CascadeMode.Stop)
                .InclusiveBetween("1", "0").When(x => !x.zt.IsNullOrWhiteSpace())
                .WithName("状态")
                .WithMessage(SysOtherConstTip.Fdcscjg_OverRange)
                 .MaximumLength(1).WithName("状态").WithMessage(SysOtherConstTip.Fdcscjg_OverLength);

FluentValidation 9.0 或者更早

使用CascadeMode.StopOnFirstFailure

RuleFor(x => x.zt)
                .Cascade(CascadeMode.StopOnFirstFailure)
                .InclusiveBetween("1", "0").When(x => !x.zt.IsNullOrWhiteSpace())
                .WithName("状态")
                .WithMessage(SysOtherConstTip.Fdcscjg_OverRange)
                 .MaximumLength(1).WithName("状态").WithMessage(SysOtherConstTip.Fdcscjg_OverLength);

使用When条件结合CascadeMode来防止规则在某些情况下运行会更简单。尽管这有时可能意味着更多的重复,但它通常更容易阅读。

NotNull 验证器

确保指定的属性不为空

 RuleFor(x => x.name).NotNull();

NotEmpty 验证器

确保指定的属性不为 null、空字符串或空格

IEnumerable(如数组、集合、列表等)上使用时,验证器确保 IEnumerable 不为空

RuleFor(x=> x.name).NotEmpty();

NotEqual 验证器

不等于

//Not equal to a particular value
RuleFor(x=> x.name).NotEqual("张三");

//Not equal to another property
RuleFor(x=> x.name).NotEqual(x=> x.Forename);

Equal 验证器

等于

//Equal to a particular value
RuleFor(customer => customer.Surname).Equal("Foo");

//Equal to another property
RuleFor(customer => customer.Password).Equal(customer => customer.PasswordConfirmation);

Length 长度验证器

RuleFor(x=> x.name).Length(1, 250); //must be between 1 and 250 chars (inclusive)

可用的格式参数占位符:

{PropertyName} = 正在验证的属性的名称
{MinLength} = 最小长度
{MaxLength} = 最大长度
{TotalLength} = 输入的字符数
{PropertyValue} = 属性的当前值

 MaxLength 最大长度/MinLength 最小长度

RuleFor(x=> x.name).MaximumLength(250); //must be 250 chars or fewer
RuleFor(x=> x.name).MinimumLength(10); //must be 10 chars or more

 LessThan 小于

//Less than a particular value
RuleFor(x=> x.CreditLimit).LessThan(100);

//Less than another property
RuleFor(x=> x.CreditLimit).LessThan(x=> x.MaxCreditLimit);

LessThanOrEqualTo

小于等于

RuleFor(x => x.ksfw).LessThanOrEqualTo(x => x.jsfw).WithMessage("开始范围必须小于结束范围");

GreaterThan 大于

//Greater than a particular value
RuleFor(x=> x.CreditLimit).GreaterThan(0);

//Greater than another property
RuleFor(x=> x.CreditLimit).GreaterThan(x=> x.MinimumCreditLimit);

GreaterThanOrEqualTo

大于等于

//Greater than a particular value
RuleFor(x=> x.CreditLimit).GreaterThanOrEqualTo(1);

//Greater than another property
RuleFor(x=> x.CreditLimit).GreaterThanOrEqualTo(x=> x.MinimumCreditLimit);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值