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