Install-Package FluentValidation

如果你使用MVC5 可以使用下面的包

Install-Package FluentValidation.MVC5

例子:

public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
//不能为空
RuleFor(customer => customer.Surname).NotEmpty(); //自定义提示语
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Pls specify a first name"); //有条件的判断
RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount); //字符串长度的限制
RuleFor(customer => customer.Address).Length(20, 250); //使用自定义验证器
RuleFor(customer => customer.PostCode).Must(BeAValidPostCode).WithMessage("Pls specify a valid postCode"); } /// <summary>
/// 自定义验证
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
private bool BeAValidPostCode(string arg)
{
throw new NotImplementedException();
}
}
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer); bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;

  

在一个属性上应用链式验证

public class CustomerValidator : AbstractValidator<Customer> {
public CustomerValidator {
RuleFor(customer => customer.Surname).NotNull().NotEqual("foo");
}
}

抛出例外

Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator(); validator.ValidateAndThrow(customer);

在复杂属性里面使用验证

public class Customer {
public string Name { get; set; }
public Address Address { get; set; }
} public class Address {
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 class AddressValidator : AbstractValidator<Address> {
public AddressValidator() {
RuleFor(address => address.Postcode).NotNull();
//etc
}
}
public class CustomerValidator : AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Name).NotNull();
RuleFor(customer => customer.Address).SetValidator(new AddressValidator())
}
}

在集合属性中使用Validator

public class OrderValidator : AbstractValidator<Order> {
public OrderValidator() {
RuleFor(x => x.ProductName).NotNull();
RuleFor(x => x.Cost).GreaterThan(0);
}
}
public class CustomerValidator : AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(x => x.Orders).SetCollectionValidator(new OrderValidator());
}
} var validator = new CustomerValidator();
var results = validator.Validate(customer);

集合验证的错误信息如下

foreach(var result in results.Errors) {
Console.WriteLine("Property name: " + result.PropertyName);
Console.WriteLine("Error: " + result.ErrorMessage);
Console.WriteLine("");
}
Property name: Orders[0].Cost
Error: 'Cost' must be greater than '0'. Property name: Orders[1].ProductName
Error: 'Product Name' must not be empty.

验证集合

RuleSet能让你选择性的验证某些验证组 忽略某些验证组

 public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleSet("Names", () => {
RuleFor(x => x.Surname).NotNull();
RuleFor(x => x.Forename).NotNull();
}); RuleFor(x => x.Id).NotEqual(0);
}
}

下面的代码我们只验证Person的Surname和ForeName两个属性

var validator = new PersonValidator();
var person = new Person();
var result = validator.Validate(person, ruleSet: "Names");

一次验证多个集合

validator.Validate(person, ruleSet: "Names,MyRuleSet,SomeOtherRuleSet")

同样你可以验证那些没有被包含到RuleSet里面的规则  这些验证是一个特殊的ruleset 名为"default"

validator.Validate(person, ruleSet: "default,MyRuleSet")

正则表达式验证器

RuleFor(customer => customer.Surname).Matches("some regex here");

Email验证器

RuleFor(customer => customer.Email).EmailAddress();

覆盖默认的属性名

RuleFor(customer => customer.Surname).NotNull().WithName("Last name");

或者

public class Person {
[Display(Name="Last name")]
public string Surname { get; set; }
}

设置验证条件

When(customer => customer.IsPreferred, () => {
RuleFor(customer => customer.CustomerDiscount).GreaterThan(0);
RuleFor(customer => customer.CreditCardNumber).NotNull();
});

写一个自定义属性验证器

public class ListMustContainFewerThanTenItemsValidator<T> : PropertyValidator {

	public ListMustContainFewerThanTenItemsValidator()
: base("Property {PropertyName} contains more than 10 items!") { } protected override bool IsValid(PropertyValidatorContext context) {
var list = context.PropertyValue as IList<T>; if(list != null && list.Count >= 10) {
return false;
} return true;
}
}
public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(person => person.Pets).SetValidator(new ListMustContainFewerThanTenItemsValidator<Pet>());
}
}

与MVC集成

1.

protected void Application_Start() {
AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes); FluentValidationModelValidatorProvider.Configure();
}

2.

[Validator(typeof(PersonValidator))]
public class Person {
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Age { get; set; }
} public class PersonValidator : AbstractValidator<Person> {
public PersonValidator() {
RuleFor(x => x.Id).NotNull();
RuleFor(x => x.Name).Length(0, 10);
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.Age).InclusiveBetween(18, 60);
}
}

3.

[HttpPost]
public ActionResult Create(Person person) { if(! ModelState.IsValid) { // re-render the view when validation failed.
return View("Create", person);
} TempData["notice"] = "Person successfully created";
return RedirectToAction("Index"); }

或者只验证指定的RuleSet

public ActionResult Save([CustomizeValidator(RuleSet="MyRuleset")] Customer cust) {
// ...
}

或者只验证指定的属性

public ActionResult Save([CustomizeValidator(Properties="Surname,Forename")] Customer cust) {
// ...
}

另外在验证的权限还有一个钩子 可以通过实现IValidatorInterceptor在验证的前后做一些工作

public interface IValidatorInterceptor {
ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext); ValidationResult AfterMvcValidation(ControllerContext controllerContext, ValidationContext validationContext, ValidationResult result);
}

  

包介绍 - Fluent Validation (用于验证)的更多相关文章

  1. Silverlight实例教程 - Validation数据验证基础属性和事件(转载)

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

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

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

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

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

  4. [LTR] RankLib.jar 包介绍

    一.介绍 RankLib.jar 是一个学习排名(Learning to rank)算法的库,目前已经实现了如下几种算法: MART RankNet RankBoost AdaRank Coordin ...

  5. laravel的Validation检索验证错误消息

    基本用法 处理错误消息 错误消息和视图 可用的验证规则 有条件地添加规则 自定义错误消息 自定义验证规则 基本用法 Laravel提供了一个简单.方便的工具,用于验证数据并通过validation类检 ...

  6. SpringMVC介绍之Validation

    对于任何一个应用而言在客户端做的数据有效性验证都不是安全有效的,这时候就要求我们在开发的时候在服务端也对数据的有效性进行验证.SpringMVC自身对数据在服务端的校验有一个比较好的支持,它能将我们提 ...

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

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

  8. Spring4相关jar包介绍(转)

    Spring4相关jar包介绍 spring-core.jar(必须):这个jar 文件包含Spring 框架基本的核心工具类.Spring 其它组件要都要使用到这个包里的类,是其它组件的基本核心,当 ...

  9. java bean validation 参数验证

    一.前言 二.几种解决方案 三.使用bean validation 自带的注解验证 四.自定义bean validation 注解验证 一.前言 在后台开发过程中,对参数的校验成为开发环境不可缺少的一 ...

随机推荐

  1. Visual Studio插件

    不定时更新,得到最好用的插件.(友情提示:安装插件时最好先备份系统) 1.Resharper 10.0.0.12.VS10x CodeMAP3.JavaScript Map Parser4.JScri ...

  2. ecshop /category.php SQL Injection Vul

    catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 Relevant Link: http://sebug.net/vuld ...

  3. C#关闭窗口代码

    if (MessageBox.Show("请您确认是否退出(Y/N)", "系统提示", MessageBoxButtons.YesNo, MessageBox ...

  4. gvim e303 无法打开 “[未命名]“的交换文件,恢复将不可能

    今天vim出现:“gvim e303 无法打开 “[未命名]“的交换文件,恢复将不可能” 解决办法: 修改你的.vimrc,增加下面的一行: set directory=.,$TEMP "默 ...

  5. JSP重定向小例子(不讲原理)

    编写一个JSP页面lucknum.jsp,产生0-9之间的随机数作为用户幸运数字,将其保存到会话中,并重定向到另一个页面showLuckNum.jsp中,在该页面中将用户的幸运数字显示出来 luckn ...

  6. Linux添加新盘扩容空间

    添加磁盘扩容操作:1.添加物理磁盘到服务器重启服务器,#fdisk -l查看识别磁盘(以/dev/sdb为例)[ ~]# fdisk -lDisk /dev/sda: 42.9 GB, 4294967 ...

  7. Hibernate 配置文件与映射文件 总结

    hibernate是一个彻底的ORM(Object Relational Mapping,对象关系映射)开源框架. 一.Hibernate配置文件详解 Hibernate配置文件有两种形式:XML与p ...

  8. Instant Python 中文缩减版

    前言 本文主要来自<Python基础教程(第2版)>([挪]Magnus Lie Hetland著,司维 曾军崴 谭颖华译 人民邮电出版社) 中的“附录A 简明版本”,对于其中的有问题之处 ...

  9. BigDecimal 类型数据的一些应用

    1.比较大小 可以通过BigDecimal的compareTo方法来进行比较.返回的结果是int类型,-1表示小于,0是等于,1是大于. 例如: if(a.compareTo(b) == -1){ a ...

  10. spring boot properties

    [转载] 代码从开发到测试要经过各种环境,开发环境,测试环境,demo环境,线上环境,各种环境的配置都不一样,同时要方便各种角色如运维,接口测试, 功能测试,全链路测试的配置,hardcode 肯定不 ...