首页 > 编程语言 >C#封装FluentValidation

C#封装FluentValidation

时间:2022-09-19 10:24:11浏览次数:70  
标签:RuleFor 封装 string 验证 C# FluentValidation userInformation public

FluentValidation是一个非常强大的用于构建强类型验证规则的 .NET 框架,帮程序员解决了繁琐的校验问题,用起来非常爽,但我还是遇到了一件非常不爽的事情,如下代码所示:

public class UserInformationValidator : AbstractValidator<UserInformation>
 {
 public UserInformationValidator()
 {
     RuleFor(o => o.UserName).Length(2, 20).WithMessage("姓名长度输入错误");
     RuleFor(o => o.Sex).Must(o=>o=="男"||o=="女").WithMessage("性别输入错误");
     RuleFor(o => o.Age).ExclusiveBetween(0, 200).WithMessage("年龄输入错误");
     RuleFor(o => o.Email).EmailAddress().WithMessage("邮箱输入错误");
  }
 }
  
  
   static void Main(string[] args)
        {

            UserInformation userInformation = new UserInformation();
            userInformation.UserName = "";
            userInformation.Sex = "女";
            userInformation.Age = 2200;
            userInformation.Email = "xxxxx";
            UserInformationValidator validationRules = new UserInformationValidator();
            var result=   validationRules.Validate(userInformation);
            if (!result.IsValid)
            {
              Console.WriteLine( string.Join(Environment.NewLine, result.Errors.Select(x => x.ErrorMessage).ToArray()));
            }

        }

我们每验证一个对象,就要新建一个类型的验证器 ,如上的UserInformationValidator ,虽然这样写逻辑上没有任何问题,但我有洁癖哈,接下来我们试着封装一下,嘿嘿,用更少的代码做更多的事情。

安装

在创建任何验证器之前,您需要在项目中添加对 FluentValidation.dll 的引用。最简单的方法是使用 NuGet 包管理器或 dotnet CLI。

模板化代码封装探索

将模板化的代码提取到父类中

仔细看上面的代码你会发现,我们每新建一个验证器,就必须要创建一个继承自AbstractValidator的类,其中T是您希望验证的类的类型,封装一个验证器父类

public class CommonVaildator<T> : AbstractValidator<T>
{

}
增加验证规则

真正的业务逻辑是写在UserInformationValidator验证器里面的,而这块代码中只需要拿到RuleFor即可,其它的统一封装到父类中,对不对,我们按照这个思路代码,封装一个长度验证器规则。首先让我们看看RuleFor的原型

  public IRuleBuilderInitial<T, TProperty> RuleFor<TProperty>(Expression<Func<T, TProperty>> expression)

它的参数是一个Func委托,那么Expression是什么呢?Experssion是一种表达式树!

表达式树是一种允许将lambda表达式表示为树状数据结构而不是可执行逻辑的代码。

在C#中是Expression来定义的,它是一种语法树,或者说是一种数据结构。其主要用于存储需要计算、运算的一种结构,它只提供存储功能,不进行运算。通常Expression是配合Lambda一起使用,这里就不做过多的解释了!那么我们就能很轻易的封装出长度验证器规则了!

     public void LengthVaildator(Expression<Func<T, string>> expression, int min, int max, string Message)
        {
            RuleFor(expression).Length(min, max).WithMessage(Message);
        }

同理,我们也可以接着封装谓词验证器规则 邮箱验证器规则等等

      public void MustVaildator(Expression<Func<T, string>> expression ,Func<T,string, bool> expression2, string Message)
        {
            RuleFor(expression).Must(expression2).WithMessage(Message);
        }
          public void EmailAddressVaildator(Expression<Func<T, string>> expression, string Message)
        {
            RuleFor(expression).EmailAddress().WithMessage(Message);
        }
封装验证方法

上面我们把验证器封装好了,那么将  var result=   validationRules.Validate(userInformation);这种验证方法封装一下不是手到擒来,代码如下

  public static string ModelValidator<T>(T source, AbstractValidator<T> sourceValidator) where T : class
        {
            var results = sourceValidator.Validate(source);
            if (!results.IsValid)
                return string.Join(Environment.NewLine, results.Errors.Select(x => x.ErrorMessage).ToArray());
            else
                return "";

        }
测试封装后的代码
              CommonVaildator<UserInformation> commonUserInformation = new CommonVaildator<UserInformation>();
            commonUserInformation.LengthVaildator(o => o.UserName, 2, 30, "姓名长度输入错误");
            commonUserInformation.MustVaildator(o => o.Sex, (user, _) => user.Sex =="男"||user.Sex=="女" , "性别输入错误");
            commonUserInformation.ExclusiveBetweenVaildator(o=>o.Age,0, 200, "年龄输入错误");
            commonUserInformation.EmailAddressVaildator(o => o.Email, "邮箱输入错误");
            string msg= VaildatorHelper.ModelValidator(userInformation, commonUserInformation);
            Console.WriteLine(msg);

这样代码看起来是不是就简洁多了,我这里就只封装了四种验证规则,其它的我就不在此封装了。

总结

文章来源于工作中的点点滴滴,这也是我的即兴封装,大家要是有更好的封装代码,欢迎交流,独乐乐不如众乐乐,本篇就说到这里啦,希望对您有帮助。

鸣谢:

https://mp.weixin.qq.com/s?__biz=MzU3Njc2NzMwNg==&mid=2247485849&idx=1&sn=00148045c104add2db906e17e9d1e677&chksm=fd0f9dbcca7814aa0672ea4f90724c6658f20697b1ccf37cffc75852ad5d2234ad17a2ea58bd#rd

标签:RuleFor,封装,string,验证,C#,FluentValidation,userInformation,public
From: https://www.cnblogs.com/yakniu/p/16706799.html

相关文章

  • CTP API开发期货自动交易平台概论
    题目比较小众,先介绍一下CTP。综合交易平台CTP(ComprehensiveTransactionPlatform)是由上海期货信息技术有限公司(上海期货交易所的全资子公司)开发的期货交易平台,CTP平台以"......
  • C++定义变量与生存周期
    作用域:作用域即一个变量可以被引用的范围,常见的作用域可分为6种:全局作用域,局部作用域,语句作用域,类作用域,命名空间作用域和文件作用域。全局变量:具有全局作用域。全局变......
  • onclick 传递参数报错
    传递代码varbtn1='<ahref="#"class="easyui-linkbuttonbtn"iconCls="icon-add"plain="true"onclick="show_detail('+obj+')">查看详情</a>';/**报错unc......
  • 【RocketMQ 课程笔记】11.RocketMQ消息发送之普通消息
    RocketMQ消息发送之普通消息架构拓扑NameServer:192.168.31.103Master:192.168.31.105Slave:192.168.31.111执行流程Master与Slave启动向NameServer注册生产者Prod......
  • 面试题:一个consumer订阅两个topic,其中一个topic消息过多堆积了,会影响另一个topic消费
     问题:一个consumer订阅两个topic,其中一个topic消息过多堆积了,会影响另一个topic消费吗答案:不影响。为什么呢?因为rocketmq首先对消息进行负载均衡(rebalance),就是将topic中......
  • windows无法输入c、v、h字母
    1、现象:1.1、英文模式无法输出c/v/h三个小写字母,但是大写可以输入,Backspace退格键也无法使用,在浏览网页时回车键会新打开一个页面1.2、中文模式不收影响1.3、切换成其他......
  • BGI-College生信入门——8、R语言基础(一)
    什么是R?R是用于统计和作图的免费软件可在各种UNIX平台、Windows和MacOS上编译和运行R的组成一种语言、带有图形的运行环境、调试器、访问某些系统功能以及运......
  • LRTimelapse for Mac(专业延时摄影渲染工具)
    lrTimelapse forMac是MACOS上的一款视频编辑软件,lrTimelapsemac是一款配合AdobeLightroom、AdobeCameraRAW和AdobeAfterEffects等程序制作延时摄影的软件。l......
  • GCC编译过程
    转:https://blog.csdn.net/chen1415886044/article/details/104537547GCC编译过程:上述gcc命令其实依次执行了四步操作:1.预处理(Preprocessing)2.编译(Compilation),3.汇......
  • 在 Mac 上拍摄截屏
    在Mac上拍摄截屏您可以捕捉整个屏幕、某个窗口或屏幕上的某一部分。 如何在Mac上拍摄截屏 要拍摄截屏,请同时按住以下三个按键:Shift、Command和3。 如......