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. linux内核增加系统调用--Beginner‘s guide

    Linux内核中设置了一组用于实现系统功能的子程序,称为系统调用.系统调用和普通库函数调用非常相似明知是系统调用由操作系统核心提供,运行于核心态,而普通的函数调用由函数库或用户自己提供,运行于用户态. ...

  2. fstream使用简介

    fstream用来进行输入/输出文件的操作. fstream file1; 定义了fstream类的一个对象file1file1.open("filename",...) 打开名为 ...

  3. iptables log

    iptables 日志 LOG target 这个功能是通过内核的日志工具完成的(rsyslogd) LOG现有5个选项 --log-level debug,info,notice,warning,w ...

  4. 如何解决Response.Redirect方法传递汉字丢失或乱码问题?

    为了确保传递的汉字被正确地接收,可以在传值之前使用Server对象的UrlEncode方法对所传递的汉字进行URL编码.代码如下: String name = Server.UrlEncode(&qu ...

  5. codevs 1013 求先序排列(二叉树遍历)

    传送门 Description 给出一棵二叉树的中序与后序排列.求出它的先序排列.(约定树结点用不同的大写字母表示,长度<=8). Input 两个字符串,分别是中序和后序(每行一个) Outp ...

  6. FZU 2191 完美的数字

    题目链接: 传送门 完美的数字 Time Limit: 1000MS     Memory Limit: 65536K 题目描述 Bob是个很喜欢数字的孩子,现在他正在研究一个与数字相关的题目,我们知 ...

  7. MooseFs-分布式文件系统系列(一)之了解并安装它

    preface 在上上家公司,曾维护过公司的MFS文件系统,主要用来存储系统日志文件,单纯的把日志当作文件存储,在当时的架构下,MFS就像一个中间站一样,这边程序生成的日志放入MFS,那边日志分析程序 ...

  8. Linux C/C++ --- “” and <> in the use of head include file(Pending Verification)

    for example: #include <stdlib.h>#include <stdio.h>#include <wiringPi.h>#include &l ...

  9. easyUI的控件

    CSS类定义: div easyui-window                               window窗口样式 属性如下: 1)       modal:是否生成模态窗口.tru ...

  10. windows7-PowerDesigner 15.1 的安装图解

    下载 PowerDesigner 15.1 的安装文件和破解文件 破解文件下载地址:http://pan.baidu.com/share/link?shareid=177873&uk=3626 ...