栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > .Net

FluentValidation学习 (.NET 6.0)

.Net 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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
    {
        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();
    });
builder.Services.AddTransient, 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; }

        /// 
        /// 里斯
        /// 
        public string Surname { get; set; }

        public string Forename { get; set; }

        public decimal Discount { get; set; }

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

    {

        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);

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/955097.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号