• 认识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项目中也支持。

  • 怎么使用:  

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

业务实体类:

 public class Person
{
public string NameField;
public int Id { get; set; }
public string Surname { get; set; }
public string Forename { get; set; } public List<Person> Children { get; set; }
public string[] NickNames { get; set; } public DateTime DateOfBirth { get; set; } public int? NullableInt { get; set; } public Person()
{
Children = new List<Person>();
Orders = new List<Order>();
} public int CalculateSalary()
{
return ;
} public Address Address { get; set; }
public IList<Order> Orders { get; set; } public string Email { get; set; }
public decimal Discount { get; set; }
public double Age { get; set; }
public int AnotherInt { get; set; } public string CreditCard { get; set; } public int? OtherNullableInt { get; set; }
} public interface IAddress
{
string Line1 { get; set; }
string Line2 { get; set; }
string Town { get; set; }
string County { get; set; }
string Postcode { get; set; }
Country Country { get; set; }
} public class Address : IAddress
{
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Town { get; set; }
public string County { get; set; }
public string Postcode { get; set; }
public Country Country { get; set; }
public int Id { get; set; }
} public class Country
{
public string Name { get; set; }
} public interface IOrder
{
decimal Amount { get; }
} public class Order : IOrder
{
public string ProductName { get; set; }
public decimal Amount { get; set; }
}

  对Person的指定验证规则:  

 using FluentValidation;

 public class CustomerValidator: AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Discount).NotEqual().When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(, );
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
} private bool BeAValidPostcode(string postcode)
{
// custom postcode validating logic goes here
}
} // 手动验证规则
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer); bool validationSucceeded = results.IsValid;
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的验证规则库中。

 // 在Global.asax.cs中的Applicaton_Start()函数中注册为asp.net mvc默认的验证规则库。

 // fluent validation
FluentValidationModelValidatorProvider provider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory());
ModelValidatorProviders.Providers.Add(provider); DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;

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

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

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

.NET业务实体类验证组件Fluent Validation的更多相关文章

  1. Fluent Validation

    .NET业务实体类验证组件Fluent Validation   认识Fluent Vaidation. 看到NopCommerce项目中用到这个组建是如此的简单,将数据验证从业务实体类中分离出来,真 ...

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

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

  3. 项目实体类使用@Data注解,但是项目业务类中使用getA(),setA()方法报错,eclipse中配置lombok

    @Data注解来源与Lombok,可以减少代码中大量的set get方法,大量减少冗余代码,但是今天部署项目时候,发现实体类使用@Data注解,但是项目业务类中使用getA(),setA()方法报错. ...

  4. mvc 实体类 自定义验证特性

    mvc 实体类验证的时候 如果有多个验证特性需要在属性上层叠很多个验证特性,显得属性特别臃肿并且也不够直观,极大地影响我使用它的兴趣,所以我想自定义一个验证特性,然后将所有需要验证的情形全部放在一个特 ...

  5. <六>面向对象分析之UML核心元素之业务实体

    一:基本概念

  6. Mybatis-plus 实体类继承关系 插入默认值

    在实际开发中,会定义一些公共字段,而这些公共字段,一般都是在进行操作的时候由程序自动将默认值插入.而公共的字段一般会被封装到一个基础的实体类中,同时实体类中会实现相应的getter setter 方法 ...

  7. WPF3.5 使用BINDINGGROUP进行实体类和集合验证

    前文介绍了自定义或系统自带的ValidationRule进行验证,这种方法对于单个元素的验证不错.很多时候,我们需要对表单(Form)进行验证,也就是对一个实体类进行验证,或者对一个集合的每项进行验证 ...

  8. 关于entityframework 自动生成实体类中加验证的属性重新生成后属性被覆盖解决办法

    1.手动创建一个部分类 (你可以手动创建 partial class, 内容为空) [MetadataType(typeof(AppleMetadata))] public partial class ...

  9. Silverlight实例教程 - 自定义扩展Validation类,验证框架的总结和建议(转载)

    Silverlight 4 Validation验证实例系列 Silverlight实例教程 - Validation数据验证开篇 Silverlight实例教程 - Validation数据验证基础 ...

随机推荐

  1. 打造私有的DNS 服务

    在企业内部一般都会有自己的DNS服务,主要为了企业方便管理,例如访问一些内部系统,控制一些网站不让访问,今天我们就说说如何打造私有的DNS服务 系统基础配置 Ubuntu14.04  内存:354M ...

  2. mysql import data slow solution---overview information

      1 SELECT SUM(DATA_LENGTH)+SUM(INDEX_LENGTH) FROM information_schema.tables WHERE TABLE_SCHEMA='dat ...

  3. centos 重启php-fpm

    centos 重启php-fpm ps -ef | grep php-fpm 查看php-fpm的配置文件,然后从配置文件查看php-fpm的pid文件,然后,  kill -SIGUSR2 `cat ...

  4. QList内存释放(看它内部存储的是否是Object,另外还有qDeleteAll)

    QList<T> 的释放分两种情况: 1.T的类型为非指针,这时候直接调用clear()方法就可以释放了,看如下测试代码 #include <QtCore/QCoreApplicat ...

  5. 【Android测试】【随笔】与 “58同城” 测试开发交流

    ◆版权声明:本文出自胖喵~的博客,转载必须注明出处. 转载请注明出处:http://www.cnblogs.com/by-dream/p/5384698.html 初衷 一直都有一个这样的想法: 虽然 ...

  6. 查看特性Attribute数据

    加载程序集 Assembly loAssembly = Assembly.Load( lcAssembly ) ;    Type[ ] laTypes = loAssembly.GetTypes(  ...

  7. 软件工程概论---max单元测试

    题目:一个单元测试,查找list[]中的最大值 编写一个程序对Largest函数进行测试,列举所有测试用例. 思路:首先确保数组不为空,和数组长度不为0,否则输入错误.根据老师所给的函数写一个主函数, ...

  8. 解决ArcGIS API for Silverlight 加载地图的内外网访问问题

    原文:解决ArcGIS API for Silverlight 加载地图的内外网访问问题 先上一个类,如下: public class BaseClass { public static string ...

  9. python入门 2014-3-21

    刚吃完饭,写一会python 准备去上课,哇咔咔! 1.python是动态类型语言,也就是说 不需要预先声明变量的类型. 不支持 自增++ , 自减--

  10. c#网页爬虫初探

    一个简单的网页爬虫例子! html代码: <head runat="server"> <title>c#爬网</title> </head ...