前言
一個 .NET 驗證框架,支持鏈?zhǔn)讲僮?,易于理解,功能完善,組件內(nèi)提供十幾種常用驗證器,可擴(kuò)展性好,支持自定義驗證器,支持本地化多語言。
項目介紹
FluentValidation 是一個開源的 .NET 庫,用于驗證對象的屬性。
它提供了一種簡單而強(qiáng)大的方式來定義和執(zhí)行驗證規(guī)則,使驗證邏輯的編寫和維護(hù)更加直觀和便捷。
相較于傳統(tǒng)的數(shù)據(jù)注解,F(xiàn)luentValidation 提供了更靈活、可擴(kuò)展的驗證規(guī)則定義方式。
通過流暢且易于理解的語法,它顯著提升了代碼的可讀性和可維護(hù)性。
項目使用
FluentValidation 11 支持以下平臺:
.NET Core 3.1、.NET 5、.NET 6、.NET 7、.NET 8、.NET Standard 2.0
1、安裝FluentValidation
通過 NuGet 包管理器或 dotnet CLI 進(jìn)行安裝。
dotnet add package FluentValidation
或NuGet 包管理器
2、Program.cs
using FluentValidation;
using FluentValidation.AspNetCore;
using MicroElements.Swashbuckle.FluentValidation.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
// Asp.Net stuff
services.AddControllers();
services.AddEndpointsApiExplorer();
// Add Swagger
services.AddSwaggerGen();
// Add FV
services.AddFluentValidationAutoValidation();
services.AddFluentValidationClientsideAdapters();
// Add FV validators
services.AddValidatorsFromAssemblyContaining<Program>();
// Add FV Rules to swagger
services.AddFluentValidationRulesToSwagger();
var app = builder.Build();
// Use Swagger
app.UseSwagger();
app.UseSwaggerUI();
app.MapControllers();
app.Run();
3、Startup.cs
public void ConfigureServices(IServiceCollection services)
{
// Asp.net stuff
services.AddControllers();
// HttpContextValidatorRegistry requires access to HttpContext
services.AddHttpContextAccessor();
// Register FV validators
services.AddValidatorsFromAssemblyContaining<Startup>(lifetime: ServiceLifetime.Scoped);
// Add FV to Asp.net
services.AddFluentValidationAutoValidation();
// Add swagger
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
});
// [Optional] Add INameResolver (SystemTextJsonNameResolver will be registered by default)
// services.AddSingleton<INameResolver, CustomNameResolver>();
// Adds FluentValidationRules staff to Swagger. (Minimal configuration)
services.AddFluentValidationRulesToSwagger();
// [Optional] Configure generation options for your needs. Also can be done with services.Configure<SchemaGenerationOptions>
// services.AddFluentValidationRulesToSwagger(options =>
// {
// options.SetNotNullableIfMinLengthGreaterThenZero = true;
// options.UseAllOffForMultipleRules = true;
// });
// Adds logging
services.AddLogging(builder => builder.AddConsole());
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
// Adds swagger
app.UseSwagger();
// Adds swagger UI
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
});
}
5、支持的驗證器
INotNullValidator(NotNull)
INotEmptyValidator(NotEmpty)
ILengthValidator(對于字符串:Length、MinimumLength、MaximumLength、ExactLength;對于數(shù)組:MinItems、MaxItems)
IRegularExpressionValidator(Email、Matches)
IComparisonValidator(GreaterThan、GreaterThanOrEqual、LessThan、LessThanOrEqual)
IBetweenValidator(InclusiveBetween、ExclusiveBetween)
6、可擴(kuò)展
可以將 FluentValidationRule 注冊到 ServiceCollection 中。
自定義規(guī)則名稱將替換具有相同名稱的默認(rèn)規(guī)則。
可以通過 FluentValidationRules.CreateDefaultRules() 獲取默認(rèn)規(guī)則的完整列表。
默認(rèn)規(guī)則列表: Required(必填) NotEmpty(非空) Length(長度) Pattern(模式) Comparison(比較) Between(區(qū)間)
new FluentValidationRule("Pattern")
{
Matches = propertyValidator => propertyValidator is IRegularExpressionValidator,
Apply = context =>
{
var regularExpressionValidator = (IRegularExpressionValidator)context.PropertyValidator;
context.Schema.Properties[context.PropertyKey].Pattern = regularExpressionValidator.Expression;
}
}
7、Swagger 模型和驗證器
public class Sample
{
public string PropertyWithNoRules { get; set; }
public string NotNull { get; set; }
public string NotEmpty { get; set; }
public string EmailAddress { get; set; }
public string RegexField { get; set; }
public int ValueInRange { get; set; }
public int ValueInRangeExclusive { get; set; }
public float ValueInRangeFloat { get; set; }
public double ValueInRangeDouble { get; set; }
}
public class SampleValidator : AbstractValidator<Sample>
{
public SampleValidator()
{
RuleFor(sample => sample.NotNull).NotNull();
RuleFor(sample => sample.NotEmpty).NotEmpty();
RuleFor(sample => sample.EmailAddress).EmailAddress();
RuleFor(sample => sample.RegexField).Matches(@"(\d{4})-(\d{2})-(\d{2})");
RuleFor(sample => sample.ValueInRange).GreaterThanOrEqualTo(5).LessThanOrEqualTo(10);
RuleFor(sample => sample.ValueInRangeExclusive).GreaterThan(5).LessThan(10);
// WARNING: Swashbuckle implements minimum and maximim as int so you will loss fraction part of float and double numbers
RuleFor(sample => sample.ValueInRangeFloat).InclusiveBetween(1.1f, 5.3f);
RuleFor(sample => sample.ValueInRangeDouble).ExclusiveBetween(2.2, 7.5f);
}
}
8、包含驗證器
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
Include(new CustomerAddressValidator());
}
}
internal class CustomerAddressValidator : AbstractValidator<Customer>
{
public CustomerAddressValidator()
{
RuleFor(customer => customer.Address).Length(20, 250);
}
}
高級用法
1、異步驗證
RuleForAsync(x => x.UserCode).MustAsync(async (usercode, cancellation) =>
{
var code = await _userService.IsUserNameUniqueAsync(usercode);
return code;
}).WithMessage("用戶編碼已存在");
2、條件驗證
When(x => x.IsAdmin, () =>
{
RuleFor(x => x.Super).NotEmpty().WithMessage("管理必須是超級管理員");
});
3、自定義驗證規(guī)則
RuleFor(x => x.Number).Custom((value, context) =>
{
if (value < 10 || value > 1000)
{
context.AddFailure("數(shù)字必須在10 到1000之間");
}
});
4、自定義錯誤消息
RuleFor(x => x.UserName).NotEmpty().WithMessage("用戶名稱不能為空")
.Matches(@"^\d{6}$").WithMessage("請輸入有效的6位數(shù)字用戶名稱");
項目地址
GitHub:https://github.com/FluentValidation/FluentValidation
總結(jié)
FluentValidation 是一個優(yōu)雅且功能強(qiáng)大的驗證庫,它在提升代碼可讀性和可維護(hù)性的同時,保持了高度的靈活性。
無論是簡單的驗證需求還是復(fù)雜的業(yè)務(wù)規(guī)則,F(xiàn)luentValidation 都能讓我們輕松確保數(shù)據(jù)的有效性。
如果大家項目中有驗證需求的,可以試一試,提高開發(fā)效率。
轉(zhuǎn)自https://www.cnblogs.com/1312mn/p/18393208
該文章在 2024/9/4 10:19:30 編輯過