FluentValidation :  https://github.com/JeremySkinner/FluentValidation

关于为何要使用,因为微软自带的模型验证有点弱,还需要自己去写一大堆的验证。

关于asp.net core的集成 我用的是 FluentValidation.AspNetCore  nuget

直接在addmvc后添加 AddFluentValidation() 就好了

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddFluentValidation();

我一般用反射注入msdi

  // 注册 Validator
var types = assembly.GetTypes().Where(p =>
p.BaseType != null && p.BaseType.GetInterfaces().Any(x => x == typeof(IValidator)));
foreach (var type in types)
{
if (type.BaseType != null)
{
var genericType = typeof(IValidator<>).MakeGenericType(type.BaseType.GenericTypeArguments[]);
services.AddTransient(genericType, type);
}
}

然后这里例举一些比较常用的方法

以下是我的模型 。

 public class UserInput
{
public string CustomerId { get; set; }
public string UserName { get; set; }
public string PhoneNumber { get; set; }
public string FullName { get; set; }
public string Description { get; set; }
public string UnionId { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}

这里是我的validator

public class UserInputVaildator : AbstractValidator<UserInput>
{
public UserInputVaildator()
{
RuleFor(m => m.UserName).NotEmpty().WithMessage("登录名是必须的"); RuleFor(m => m.CustomerId).NotEmpty().WithMessage("客户Id是必须的");
//当手机号为空的时候就不会再去验证手机号格式是否 因为默认是不会停止验证。
RuleFor(m => m.PhoneNumber)
.Cascade(CascadeMode.StopOnFirstFailure)
.NotEmpty().WithMessage("手机号是必须的")
.PhoneNumber().WithMessage("手机格式不正确");
//这里的意思是当 邮箱不为空时采取验证邮箱格式是否正确
RuleFor(m => m.Email)
.EmailAddress().When(m => !string.IsNullOrWhiteSpace(m.Email)).WithMessage("邮箱格式不正确");
}
}

当然,还有一些其他的东西

   public class TestInput
{
public string Grant { get; set; } public int Number { get; set; }
}
public class TestInputValidator : AbstractValidator<TestInput>
{
public TestInputValidator()
{
      
RuleSet("test", () =>
{
RuleFor(m => m.Number).GreaterThan().WithMessage("Number要大于0");
});
RuleFor(m => m.Grant).NotEmpty().WithMessage("Grant不能为空");
}
}

规则的设置,可以适应不同的验证场景,对同一个Model进行不同的验证

[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
//
[HttpGet]
public IActionResult Get([FromQuery]TestInput input)
{
return Ok();
} //规则的设置,可以适应不同的验证场景,对同一个Model进行不同的验证
[HttpPost]
public IActionResult Index([FromBody][CustomizeValidator(RuleSet = "test")]TestInput input)
{
return Ok("");
}
}

父类,接口的验证

public class CustomerCreateInput : ClientInput, ICustomerInput{
//具体的实现接口
} public class CustomerInputInterfaceValidator : AbstractValidator<ICustomerInput>{
  //具体 接口 验证逻辑
} public class ClientInputVaildators : AbstractValidator<ClientInput>{
//集体 基类 验证逻辑
} //那么我该如果重用接口和基类的验证逻辑
public class CustomerCreateInputValidator : AbstractValidator<CustomerCreateInput>
{
public CustomerCreateInputValidator()
{
//只需要包含进来
Include(new CustomerInputInterfaceValidator());
Include(new ClientInputVaildators());
}
}
这里就有个问题,如果包含的验证类中包含了 RuleSet,那么该如何启用。因为默认不会启用,这个问题,我也不知道 (~ ̄▽ ̄)~ 只能说我也不太精通,昨天刚刚开始用。

关于简单的 FluentValidation 验证的更多相关文章

  1. .NET平台开源项目速览(10)FluentValidation验证组件深入使用(二)

    在上一篇文章:.NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(一) 中,给大家初步介绍了一下FluentValidation验证组件的使用情况.文章从构建间的验证器开 ...

  2. .NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(一)

    在文章:这些.NET开源项目你知道吗?让.NET开源来得更加猛烈些吧!(第二辑)中,给大家初步介绍了一下FluentValidation验证组件.那里只是概述了一下,并没有对其使用和强大功能做深入研究 ...

  3. NET平台开源项目速览(6)FluentValidation验证组件介绍与入门(转载)

    原文地址:http://www.cnblogs.com/asxinyu/p/dotnet_Opensource_project_FluentValidation_1.html 阅读目录 1.基本介绍 ...

  4. ASP.NET MVC中使用FluentValidation验证实体

    1.FluentValidation介绍 FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的 ...

  5. jQuery validate 根据 asp.net MVC的验证提取简单快捷的验证方式(jquery.validate.unobtrusive.js)

    最近在学习asp.netMVC,发现其中的验证方式书写方便快捷,应用简单,易学好懂. 验证方式基于jQuery的validate 验证方式,也可以说是对jQuery validate的验证方式的扩展, ...

  6. shiro 简单的身份验证 案例

    Apache Shiro是Java的一个安全框架,Shiro可以帮助我们完成:认证.授权.加密.会话管理.与Web集成.缓存等. 简单的身份验证 项目目录: 首先,在shiro.ini里配置了用户名和 ...

  7. jQuery结合Ajax实现简单的前端验证和服务端查询

    上篇文章写了简单的前端验证由传统的JavaScript转向流畅的jQuery滑动验证,现在拓展一下,使用Ajax实现用户体验比较好的异步查询,同样还是从建立一个简单的表单开始 <form nam ...

  8. cookie小栗子-实现简单的身份验证

    关于Cookie Cookie是一种能够让网站Web服务器把少量数据储存到客户端的硬盘或内存里,或是从客户端的硬盘里读取数据的一种技术. 用来保存客户浏览器请求服务器页面的请求信息,可以在HTTP返回 ...

  9. ASP.NET MVC中使用FluentValidation验证实体(转载)

    1.FluentValidation介绍 FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的 ...

随机推荐

  1. activiti工作流(传智播客)

    1:工作流的概念   说明: 1) 假设:这两张图就是华谊兄弟的请假流程图  2) 图的组成部分:  A. 人物:范冰冰 冯小刚 王中军  B. 事件(动作):请假.批准.不批准     工作流(Wo ...

  2. nginx-ingress之server-snippet用法

    apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: nginx.ingress.kubernetes.io/serv ...

  3. Jenkins使用过程中注意事项

    jenkins自动部署注意事项: 安装jenkins https://blog.csdn.net/qq_37372007/article/details/81586751 1.当提示错误ERROR: ...

  4. MySQL Replication--事务组提交和多线程复制

    事务组提交和多线程复制 在MySQL 5.7版本引入基于LOGICAL_CLOCK的多线程复制,依赖于BINLOG事件中的last_committed属性,该last_committed属性是否与事务 ...

  5. 【Feign调用异常】org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported

    一.异常场景描述 明明是post请求,为啥到达服务器后就变成了get请求 2019-05-30 18:07:17.055 [http-nio-10650-exec-4] ERROR c.x.xcaut ...

  6. ExecutorService java多线程分割list运行

    调用方法 int threadNum = 7; while(true) { List<FaceAnalyseImage> list = faceAnalyseImageMapper.sel ...

  7. metasploit 一款开源的渗透测试框架

    渗透神器漏洞利用框架metasploit from: https://zhuanlan.zhihu.com/p/30743401 metasploit是一款开源的渗透测试框架软件也是一个逐步发展与成熟 ...

  8. Python开发应用-操作excel

    一. openpyxl读 95%的时间使用的是这个模块,目前excel处理的模块,只有这个还在维护 1.workBook workBook=openpyxl.load_workbook('path(. ...

  9. 【CLAA系列】CLAA 通讯过程

    名词: MSP:中兴服务器 CS:客户服务器,也就是我们的服务器 GW:网关,这里默认是中兴的网关 Chip:芯片,这里特指包含了Lora标准通讯模块,且针对CLAA做过特殊优化的芯片. Lora:L ...

  10. Pivotal Greenplum 6.0 新特性介绍

    Pivotal Greenplum 6.0 新特性介绍   在1月12日举办的Greenplum开源有道智数未来技术研讨会上,Pivotal中国研发中心Greenplum 产品经理李阳向大家介绍了Pi ...