.NET业务实体类验证组件Fluent Validation

 
  • 认识Fluent Vaidation.

  看到NopCommerce项目中用到这个组建是如此的简单,将数据验证从业务实体类中分离出来,真是一个天才的想法,后来才知道这个东西是一个开源的轻量级验证组建。

  Fluent Validation 翻译为:流畅验证

  开源Codeplex其主页简介:该组件是一个轻量级的.NET类库,使用流畅的接口定义和lambda表达式为构建一个业务类的验证规则(A small validation library for .NET that uses a fluent interface and lambda expression for building validation rules for you business objects.)

  这个类库不仅仅可以使用的asp.net mvc项目中,普通的类库中也可以使用,当然在asp.net form项目中也支持。

  • 怎么使用:  

  是不是好用,还要看使用时是否真的像其官网建议描述一样。我比较喜欢其官网上的例子,一眼就能看出用法上的感觉,绝对是如其名,流畅,这个也一种解释型语言常见的的一种用法,无限的对一个类型支持无限度个属性扩展。

业务实体类:

 1 public class Person
2 {
3 public string NameField;
4 public int Id { get; set; }
5 public string Surname { get; set; }
6 public string Forename { get; set; }
7
8 public List<Person> Children { get; set; }
9 public string[] NickNames { get; set; }
10
11 public DateTime DateOfBirth { get; set; }
12
13 public int? NullableInt { get; set; }
14
15 public Person()
16 {
17 Children = new List<Person>();
18 Orders = new List<Order>();
19 }
20
21 public int CalculateSalary()
22 {
23 return 20;
24 }
25
26 public Address Address { get; set; }
27 public IList<Order> Orders { get; set; }
28
29 public string Email { get; set; }
30 public decimal Discount { get; set; }
31 public double Age { get; set; }
32 public int AnotherInt { get; set; }
33
34 public string CreditCard { get; set; }
35
36 public int? OtherNullableInt { get; set; }
37 }
38
39 public interface IAddress
40 {
41 string Line1 { get; set; }
42 string Line2 { get; set; }
43 string Town { get; set; }
44 string County { get; set; }
45 string Postcode { get; set; }
46 Country Country { get; set; }
47 }
48
49 public class Address : IAddress
50 {
51 public string Line1 { get; set; }
52 public string Line2 { get; set; }
53 public string Town { get; set; }
54 public string County { get; set; }
55 public string Postcode { get; set; }
56 public Country Country { get; set; }
57 public int Id { get; set; }
58 }
59
60 public class Country
61 {
62 public string Name { get; set; }
63 }
64
65 public interface IOrder
66 {
67 decimal Amount { get; }
68 }
69
70 public class Order : IOrder
71 {
72 public string ProductName { get; set; }
73 public decimal Amount { get; set; }
74 }

  对Person的指定验证规则:  

 1 using FluentValidation;
2
3 public class CustomerValidator: AbstractValidator<Customer>
4 {
5 public CustomerValidator()
6 {
7 RuleFor(customer => customer.Surname).NotEmpty();
8 RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
9 RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
10 RuleFor(customer => customer.Address).Length(20, 250);
11 RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
12 }
13
14 private bool BeAValidPostcode(string postcode)
15 {
16 // custom postcode validating logic goes here
17 }
18 }
19
20 // 手动验证规则
21 Customer customer = new Customer();
22 CustomerValidator validator = new CustomerValidator();
23 ValidationResult results = validator.Validate(customer);
24
25 bool validationSucceeded = results.IsValid;
26 IList<ValidationFailure> failures = results.Errors;
  • Flent validation怎么与asp.net mvc验证库整合?

  如果在asp.net mvc中现实中这么用,可能会有很多人不会知道他,我们知道Asp.net MVC项目中有自己的验证机构[企业库VAB(Validation Application Block),基于Attribute声明式验证],其使用方法,也被我们都一直很认可,但其也有很多不够灵活的,但Fluent Validation确实更灵活一点。使用起来多变性,流畅,而且验证规则是一个单独的类,是和业务实体对象分类的,我们不需要翔VAB一样,需要在业务实体类上使用Attribute注册验证规则。

  既然其不是ASP.NET MVC的默认验证规则类库,我们就需要注册到ASP.NET MVC的验证规则库中。

1 // 在Global.asax.cs中的Applicaton_Start()函数中注册为asp.net mvc默认的验证规则库。
2
3 // fluent validation
4 FluentValidationModelValidatorProvider provider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory());
5 ModelValidatorProviders.Providers.Add(provider);
6
7 DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

注意:
  1,)作为Fluent Validation验证规则类须继承AbstractValidator<T>;

  2,)我们也可以仿照NopCommerce的处理方法,对AttributeValidatorFactory类的Validator(Type type)函数重写,在特殊的业务环境下支持其他验证规则。

希望更多牛人们给点建议!

 
分类: C#

Fluent Validation的更多相关文章

  1. MVC学习系列12---验证系列之Fluent Validation

    前面两篇文章学习到了,服务端验证,和客户端的验证,但大家有没有发现,这两种验证各自都有弊端,服务器端的验证,验证的逻辑和代码的逻辑混合在一起了,如果代码量很大的话,以后维护扩展起来,就不是很方便.而客 ...

  2. .NET业务实体类验证组件Fluent Validation

    认识Fluent Vaidation. 看到NopCommerce项目中用到这个组建是如此的简单,将数据验证从业务实体类中分离出来,真是一个天才的想法,后来才知道这个东西是一个开源的轻量级验证组建. ...

  3. Fluent Validation + NInject3 + MVC5

    Fluent Validation + NInject + MVC - Why & How : Part 1 http://fluentvalidation.codeplex.com/ htt ...

  4. Fluent Validation with Web Api 2

    using FluentValidation;using FluentValidation.Attributes;using System;using System.Collections.Gener ...

  5. Asp.net core 学习笔记 Fluent Validation

    之前就有在 .net 时代介绍过了. 这个 dll 也支持 .net core 而且一直有人维护. 对比 data annotation 的 validation, 我越来越觉得这个 fluent 好 ...

  6. 包介绍 - Fluent Validation (用于验证)

    Install-Package FluentValidation 如果你使用MVC5 可以使用下面的包 Install-Package FluentValidation.MVC5 例子: public ...

  7. Fluent Validation For .NET

    //.net 中数据验证,一个开源的项目,直接下载 1 using FluentValidation; public class CustomerValidator: AbstractValidato ...

  8. MVC学习系列4--@helper辅助方法和用户自定义HTML方法

    在HTML Helper,帮助类的帮助下,我们可以动态的创建HTML控件.HTML帮助类是在视图中,用来呈现HTML内容的.HTML帮助类是一个方法,它返回的是string类型的值. HTML帮助类, ...

  9. [转]NopCommerce之旅: 应用启动

    本文转自:http://www.cnblogs.com/devilsky/p/5359881.html 我的NopCommerce之旅(6): 应用启动   一.基础介绍 Global.asax 文件 ...

随机推荐

  1. ruby 删除文件夹(包括文件夹中的文件夹和文件)

    def deleteDirectory(dirPath) if File.directory?(dirPath) puts "是文件夹"; Dir.foreach(dirPath) ...

  2. iOS 生成随机颜色(UIColor)

    #import <UIKit/UIKit.h> @interface UIColor (RandomColor) +(UIColor *) randomColor; @end #impor ...

  3. 2014年辛星全然解读html第八节

    经过前面七节的学习,我感觉大家的HTML的功底也差点儿相同了,并且我特别的删去了某些东西,比方框架,假设回到几年前,那么框架是很流行的,可是如今都到了2014年了,这些东西早就该被遗忘了,因此,我果断 ...

  4. CentOS安装KVM步骤虚拟机,绝对实用!

    KVM(Kernel-based Virtual Machine)速记.这是rhel5.4最新的虚拟化技术启动,现在只支持红帽64位rhel5.4在执行KVM,硬件必须支持同一时间VT技术,网上找 ...

  5. 【Struts2学习笔记(2)】Action默认值和配置Action于result各种转发类型

    一.Action缺省配置值 <span style="font-size:18px;"><package name="itcast" name ...

  6. SharePoint 如何使自己的网页自动跳转

    SharePoint 如何使自己的网页自动跳转         SharePoint自动制作自己的网页跳的很easy,只有在页面上要添加一个Web部分--内容编辑器,对应的js代码就可以.       ...

  7. AspNetPager常用属性及一些样式

    AlwaysShow 总是显示分页控件,即使要分页的数据只有一页 AlwaysShowFirsLastPageNumbr 是否总是显示第一页和最后一页数字页索引按钮 BackImageUrl 面板的背 ...

  8. windows下系统移植到linux下出现的问题

    今天遇到了一个之前没有遇到的问题,记录一下. 我们是在windows下进行开发的,最终系统是部署在linux服务器上. 在windows一切正常,但是部署到linux下时,有些功能不能用了.通过log ...

  9. linux_java_redis_postgresql_常用命令

     redis 常用语法telnet 192.168.18.210 6379keys *llen队列名称llen 队列名称 postgresql常用语法psql -h192.168.18.210 -Up ...

  10. P31RestKit.dll 2.0 Unity3d json

    using System.Collections.Generic; using UnityEngine; using System.Collections; using Prime31; public ...