百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

【分享】.NET 最好用的验证组件 FluentValidation

ztj100 2024-12-25 16:49 15 浏览 0 评论

前言

今天给广大网友分享一款 .NET 验证框架——FluentValidation。框架支持链式操作,易于理解,功能完善,组件内提供十几种常用验证器,可扩展性好,支持自定义验证器,支持本地化多语言。

项目介绍

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 进行安装。

Bash
dotnet add package FluentValidation

或NuGet 包管理器

2、Program.cs

Bash
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");
    });
}

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(区间)

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、自定义验证规则

RuleFor(x => x.Number).Custom((value, context) =>
{
    if (value < 10 || value > 1000)
    {
        context.AddFailure("数字必须在10 到1000之间");
    }
});

4、自定义错误消息

RuleFor(x => x.UserName).NotEmpty().WithMessage("用户名称不能为空")
       .Matches(@"^\d{6}#34;).WithMessage("请输入有效的6位数字用户名称"); 

项目地址

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

总结

FluentValidation 是一个优雅且功能强大的验证库,它在提升代码可读性和可维护性的同时,保持了高度的灵活性。

无论是简单的验证需求还是复杂的业务规则,FluentValidation 都能让我们轻松确保数据的有效性。

如果大家项目中有验证需求的,可以试一试,提高开发效率。

最后

如果你觉得这篇文章对你有帮助,不妨点个赞支持一下!你的支持是我继续分享知识的动力。如果有任何疑问或需要进一步的帮助,欢迎随时留言。

相关推荐

能量空间物质相互转化途径(能量与空间转换相对论公式)

代码实现<!DOCTYPEhtml><htmllang="zh"><head>...

从零开始的Flex布局掌握(flex布局实战)

前言在现代网页设计中,布局是一个至关重要的环节,在过去的一段时间里,页面的布局还都是通过table...

flex布局在css中的使用,一看就会!

1.认识flex布局我们在写前端页面的时候可能会遇到这样的问题:同样的一个页面在1920x1080的大屏幕中显示正常,但是在1366x768的小屏幕中却显示的非常凌乱。...

前端入门——弹性布局(Flex)(web前端弹性布局)

前言在css3Flex技术出现之前制作网页大多使用浮动(float)、定位(position)以及显示(display)来布局页面,随着互联网快速发展,移动互联网的到来,已无法满足需求,它对于那些...

CSS Flex 容器完整指南(css flex-shrink)

概述CSSFlexbox是现代网页布局的强大工具。本文详细介绍用于flex容器的CSS属性:...

Centos 7 network.service 启动失败

执行systemctlrestartnetwork重启网络报如下错误:Jobfornetwork.servicefailedbecausethecontrolprocessex...

CentOS7 执行systemctl start iptables 报错:...: Unit not found.

#CentOS7执行systemctlstartiptables报错:Failedtostartiptables.service:Unitnotfound.在CentOS7中...

systemd入门6:journalctl的详细介绍

该来的总会来的,逃是逃不掉的。话不多说,man起来:manjournalctl洋洋洒洒几百字的描述,是说journalctl是用来查询systemd日志的,这些日志都是systemd-journa...

Linux上的Systemctl命令(systemctl命令详解)

LinuxSystemctl是一个系统管理守护进程、工具和库的集合,用于取代SystemV、service和chkconfig命令,初始进程主要负责控制systemd系统和服务管理器。通过Syste...

如何使用 systemctl 管理服务(systemctl添加服务)

systemd是一个服务管理器,目前已经成为Linux发行版的新标准。它使管理服务器变得更加容易。了解并利用组成systemd的工具将有助于我们更好地理解它提供的便利性。systemctl的由来...

内蒙古2024一分一段表(文理)(内蒙古考生2020一分一段表)

分数位次省份...

2016四川高考本科分数段人数统计,看看你有多少竞争对手

昨天,四川高考成绩出炉,全省共220,196人上线本科,相信每个考生都查到了自己的成绩。而我们都清楚多考1分就能多赶超数百人,那你是否知道,和你的分数一样的人全省有几个人?你知道挡在你前面的有多少人?...

难怪最近电脑卡爆了,微软确认Win11资源管理器严重BUG

近期,Win11操作系统的用户普遍遭遇到了一个令人头大的问题:电脑卡顿,CPU占用率异常增高。而出现该现象的原因竟然与微软最近的一次补丁更新有关。据报道,微软已经确认,问题源于Win11资源管...

微软推送Win11正式版22621.1702(KB5026372)更新

IT之家5月10日消息,微软今天推送了最新的Win11系统更新,21H2正式版通道推送了KB5026368补丁,版本号升至22000.1936,22H2版本推送了KB50263...

骗子AI换脸冒充亲戚,女子转账10万元后才发现异常……

“今天全靠你们,不然我这被骗的10万元肯定就石沉大海了。”7月19日,家住石马河的唐女士遭遇了“AI”换脸诈骗,幸好她报警及时,民警对其转账给骗子的钱成功进行止付。当天13时许,唐女士收到一条自称是亲...

取消回复欢迎 发表评论: