翼度科技»论坛 编程开发 .net 查看内容

.NET 最好用的验证组件 FluentValidation

5

主题

5

帖子

15

积分

新手上路

Rank: 1

积分
15
前言

一个 .NET 验证框架,支持链式操作,易于理解,功能完善,组件内提供十几种常用验证器,可扩展性好,支持自定义验证器,支持本地化多语言。
项目介绍

FluentValidation 是一个开源的 .NET 库,用于验证对象的属性。
它提供了一种简单而强大的方式来定义和执行验证规则,使验证逻辑的编写和维护更加直观和便捷。
相较于传统的数据注解,FluentValidation 提供了更灵活、可扩展的验证规则定义方式。
通过流畅且易于理解的语法,它显著提升了代码的可读性和可维护性。
项目使用

FluentValidation 11 支持以下平台:
.NET Core 3.1、.NET 5、.NET 6、.NET 7、.NET 8、.NET Standard 2.0
1、安装FluentValidation
通过 NuGet 包管理器或 dotnet CLI 进行安装。
  1. dotnet add package FluentValidation
复制代码
或NuGet 包管理器
2、Program.cs
  1. using FluentValidation;
  2. using FluentValidation.AspNetCore;
  3. using MicroElements.Swashbuckle.FluentValidation.AspNetCore;
  4. var builder = WebApplication.CreateBuilder(args);
  5. var services = builder.Services;
  6. // Asp.Net stuff
  7. services.AddControllers();
  8. services.AddEndpointsApiExplorer();
  9. // Add Swagger
  10. services.AddSwaggerGen();
  11. // Add FV
  12. services.AddFluentValidationAutoValidation();
  13. services.AddFluentValidationClientsideAdapters();
  14. // Add FV validators
  15. services.AddValidatorsFromAssemblyContaining<Program>();
  16. // Add FV Rules to swagger
  17. services.AddFluentValidationRulesToSwagger();
  18. var app = builder.Build();
  19. // Use Swagger
  20. app.UseSwagger();
  21. app.UseSwaggerUI();
  22. app.MapControllers();
  23. app.Run();
复制代码
3、Startup.cs
  1. public void ConfigureServices(IServiceCollection services)
  2. {
  3.     // Asp.net stuff
  4.     services.AddControllers();
  5.    
  6.     // HttpContextValidatorRegistry requires access to HttpContext
  7.     services.AddHttpContextAccessor();
  8.     // Register FV validators
  9.     services.AddValidatorsFromAssemblyContaining<Startup>(lifetime: ServiceLifetime.Scoped);
  10.     // Add FV to Asp.net
  11.     services.AddFluentValidationAutoValidation();
  12.     // Add swagger
  13.     services.AddSwaggerGen(c =>
  14.     {
  15.         c.SwaggerDoc("v1", new OpenApiInfo { Title = "My API", Version = "v1" });
  16.     });
  17.     // [Optional] Add INameResolver (SystemTextJsonNameResolver will be registered by default)
  18.     // services.AddSingleton<INameResolver, CustomNameResolver>();
  19.     // Adds FluentValidationRules staff to Swagger. (Minimal configuration)
  20.     services.AddFluentValidationRulesToSwagger();
  21.     // [Optional] Configure generation options for your needs. Also can be done with services.Configure<SchemaGenerationOptions>
  22.     // services.AddFluentValidationRulesToSwagger(options =>
  23.     // {
  24.     //     options.SetNotNullableIfMinLengthGreaterThenZero = true;
  25.     //     options.UseAllOffForMultipleRules = true;
  26.     // });
  27.     // Adds logging
  28.     services.AddLogging(builder => builder.AddConsole());
  29. }
  30. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  31. {
  32.     app.UseRouting();
  33.     app.UseEndpoints(endpoints =>
  34.     {
  35.         endpoints.MapControllers();
  36.     });
  37.     // Adds swagger
  38.     app.UseSwagger();
  39.     // Adds swagger UI
  40.     app.UseSwaggerUI(c =>
  41.     {
  42.         c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
  43.     });
  44. }
复制代码
4、版本兼容
5、支持的验证器

  • INotNullValidator(NotNull)
  • INotEmptyValidator(NotEmpty)
  • ILengthValidator(对于字符串:Length、MinimumLength、MaximumLength、ExactLength;对于数组:MinItems、MaxItems)
  • IRegularExpressionValidator(Email、Matches)
  • IComparisonValidator(GreaterThan、GreaterThanOrEqual、LessThan、LessThanOrEqual)
  • IBetweenValidator(InclusiveBetween、ExclusiveBetween)
6、可扩展
可以将 FluentValidationRule 注册到 ServiceCollection 中。
自定义规则名称将替换具有相同名称的默认规则。
可以通过 FluentValidationRules.CreateDefaultRules() 获取默认规则的完整列表。
默认规则列表: Required(必填) NotEmpty(非空) Length(长度) Pattern(模式) Comparison(比较) Between(区间)
  1. new FluentValidationRule("Pattern")
  2. {
  3.     Matches = propertyValidator => propertyValidator is IRegularExpressionValidator,
  4.     Apply = context =>
  5.     {
  6.         var regularExpressionValidator = (IRegularExpressionValidator)context.PropertyValidator;
  7.         context.Schema.Properties[context.PropertyKey].Pattern = regularExpressionValidator.Expression;
  8.     }
  9. }
复制代码
7、Swagger 模型和验证器
  1. public class Sample
  2. {
  3.     public string PropertyWithNoRules { get; set; }
  4.     public string NotNull { get; set; }
  5.     public string NotEmpty { get; set; }
  6.     public string EmailAddress { get; set; }
  7.     public string RegexField { get; set; }
  8.     public int ValueInRange { get; set; }
  9.     public int ValueInRangeExclusive { get; set; }
  10.     public float ValueInRangeFloat { get; set; }
  11.     public double ValueInRangeDouble { get; set; }
  12. }
  13. public class SampleValidator : AbstractValidator<Sample>
  14. {
  15.     public SampleValidator()
  16.     {
  17.         RuleFor(sample => sample.NotNull).NotNull();
  18.         RuleFor(sample => sample.NotEmpty).NotEmpty();
  19.         RuleFor(sample => sample.EmailAddress).EmailAddress();
  20.         RuleFor(sample => sample.RegexField).Matches(@"(\d{4})-(\d{2})-(\d{2})");
  21.         RuleFor(sample => sample.ValueInRange).GreaterThanOrEqualTo(5).LessThanOrEqualTo(10);
  22.         RuleFor(sample => sample.ValueInRangeExclusive).GreaterThan(5).LessThan(10);
  23.         // WARNING: Swashbuckle implements minimum and maximim as int so you will loss fraction part of float and double numbers
  24.         RuleFor(sample => sample.ValueInRangeFloat).InclusiveBetween(1.1f, 5.3f);
  25.         RuleFor(sample => sample.ValueInRangeDouble).ExclusiveBetween(2.2, 7.5f);
  26.     }
  27. }
复制代码
8、包含验证器
  1. public class CustomerValidator : AbstractValidator<Customer>
  2. {
  3.     public CustomerValidator()
  4.     {
  5.         RuleFor(customer => customer.Surname).NotEmpty();
  6.         RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
  7.         Include(new CustomerAddressValidator());
  8.     }
  9. }
  10. internal class CustomerAddressValidator : AbstractValidator<Customer>
  11. {
  12.     public CustomerAddressValidator()
  13.     {
  14.         RuleFor(customer => customer.Address).Length(20, 250);
  15.     }
  16. }
复制代码
高级用法

1、异步验证
  1. RuleForAsync(x => x.UserCode).MustAsync(async (usercode, cancellation) =>
  2. {
  3.     var code = await _userService.IsUserNameUniqueAsync(usercode);
  4.     return code;
  5. }).WithMessage("用户编码已存在");
复制代码
2、条件验证
  1. When(x => x.IsAdmin, () =>
  2. {
  3.     RuleFor(x => x.Super).NotEmpty().WithMessage("管理必须是超级管理员");
  4. });
复制代码
3、自定义验证规则
  1. RuleFor(x => x.Number).Custom((value, context) =>
  2. {
  3.     if (value < 10 || value > 1000)
  4.     {
  5.         context.AddFailure("数字必须在10 到1000之间");
  6.     }
  7. });
复制代码
4、自定义错误消息
  1. RuleFor(x => x.UserName).NotEmpty().WithMessage("用户名称不能为空")
  2.        .Matches(@"^\d{6}$").WithMessage("请输入有效的6位数字用户名称");
复制代码
项目地址

GitHub:https://github.com/FluentValidation/FluentValidation
总结

FluentValidation 是一个优雅且功能强大的验证库,它在提升代码可读性和可维护性的同时,保持了高度的灵活性。
无论是简单的验证需求还是复杂的业务规则,FluentValidation 都能让我们轻松确保数据的有效性。
如果大家项目中有验证需求的,可以试一试,提高开发效率。
最后

如果你觉得这篇文章对你有帮助,不妨点个赞支持一下!你的支持是我继续分享知识的动力。如果有任何疑问或需要进一步的帮助,欢迎随时留言。
也可以加入微信公众号[DotNet技术匠] 社区,与其他热爱技术的同行一起交流心得,共同成长!优秀是一种习惯,欢迎大家留言学习!

 

来源:https://www.cnblogs.com/1312mn/p/18393208
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x

举报 回复 使用道具