NET MVC中使用FluentValidation
ASP.NET MVC中使用FluentValidation验证实体
1、FluentValidation介绍
FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的验证方式,同时FluentValidation还提供了表达式链式语法。
2、安装FluentValidation
FluentValidation地址:http://fluentvalidation.codeplex.com/
使用Visual Studio的管理NuGet程序包安装FluentValidation及FluentValidation.Mvc
3、通过ModelState使用FluentValidation验证
项目解决方案结构图:
实体类Customer.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace Libing.Portal.Web.Models.Entities
{
public class Customer
{
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
public float? Discount { get; set; }
public bool HasDiscount { get; set; }
}
}

数据验证类CustomerValidator.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using FluentValidation; using Libing.Portal.Web.Models.Entities; namespace Libing.Portal.Web.Models.Validators
{
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(customer => customer.CustomerName).NotNull().WithMessage("客户名称不能为空");
RuleFor(customer => customer.Email)
.NotEmpty().WithMessage("邮箱不能为空")
.EmailAddress().WithMessage("邮箱格式不正确");
RuleFor(customer => customer.Discount)
.NotEqual(0)
.When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address)
.NotEmpty()
.WithMessage("地址不能为空")
.Length(20, 50)
.WithMessage("地址长度范围为20-50字节");
}
}
}

控制器类CustomerController.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; using FluentValidation.Results; using Libing.Portal.Web.Models.Entities;
using Libing.Portal.Web.Models.Validators; namespace Libing.Portal.Web.Controllers
{
public class CustomerController : Controller
{
public ActionResult Index()
{
return View();
} public ActionResult Create()
{
return View();
} [HttpPost]
public ActionResult Create(Customer customer)
{
CustomerValidator validator = new CustomerValidator();
ValidationResult result = validator.Validate(customer); if (!result.IsValid)
{
result.Errors.ToList().ForEach(error =>
{
ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
});
} if (ModelState.IsValid)
{
return RedirectToAction("Index");
} return View(customer);
}
}
}

View页面Create.cshtml,该页面为在添加View时选择Create模板自动生成:

@model Libing.Portal.Web.Models.Entities.Customer @{
Layout = null;
} <!DOCTYPE html> <html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Create</title>
</head>
<body>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken() <div class="form-horizontal">
<h4>Customer</h4>
<hr />
@Html.ValidationSummary(true) <div class="form-group">
@Html.LabelFor(model => model.CustomerName, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.CustomerName)
@Html.ValidationMessageFor(model => model.CustomerName)
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Email, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Address, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Address)
@Html.ValidationMessageFor(model => model.Address)
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Postcode, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Postcode)
@Html.ValidationMessageFor(model => model.Postcode)
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.Discount, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Discount)
@Html.ValidationMessageFor(model => model.Discount)
</div>
</div> <div class="form-group">
@Html.LabelFor(model => model.HasDiscount, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.HasDiscount)
@Html.ValidationMessageFor(model => model.HasDiscount)
</div>
</div> <div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
</body>
</html>

运行效果:
4、通过设置实体类Attribute与验证类进行验证
修改实体类Customer.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; using FluentValidation.Attributes; using Libing.Portal.Web.Models.Validators; namespace Libing.Portal.Web.Models.Entities
{
[Validator(typeof(CustomerValidator))]
public class Customer
{
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
public float? Discount { get; set; }
public bool HasDiscount { get; set; }
}
}

修改Global.asax.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing; using FluentValidation.Attributes;
using FluentValidation.Mvc; namespace Libing.Portal.Web
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes); // FluentValidation设置
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Add(new FluentValidationModelValidatorProvider(new AttributedValidatorFactory()));
}
}
}

NET MVC中使用FluentValidation的更多相关文章
- ASP.NET MVC中使用FluentValidation验证实体
1.FluentValidation介绍 FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的 ...
- ASP.NET MVC中使用FluentValidation验证实体(转载)
1.FluentValidation介绍 FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的 ...
- 如何在 ASP.NET MVC 中集成 AngularJS(3)
今天来为大家介绍如何在 ASP.NET MVC 中集成 AngularJS 的最后一部分内容. 调试路由表 - HTML 缓存清除 就在我以为示例应用程序完成之后,我意识到,我必须提供两个版本的路由表 ...
- 如何在 ASP.NET MVC 中集成 AngularJS(1)
介绍 当涉及到计算机软件的开发时,我想运用所有的最新技术.例如,前端使用最新的 JavaScript 技术,服务器端使用最新的基于 REST 的 Web API 服务.另外,还有最新的数据库技术.最新 ...
- MVC 中集成 AngularJS1
在 ASP.NET MVC 中集成 AngularJS(1) 介绍 当涉及到计算机软件的开发时,我想运用所有的最新技术.例如,前端使用最新的 JavaScript 技术,服务器端使用最新的基于 R ...
- ASP.NET Core WebApi中使用FluentValidation验证数据模型
原文链接:Common features in ASP.NET Core 2.1 WebApi: Validation 作者:Anthony Giretti 译者:Lamond Lu 介绍 验证用户输 ...
- 【翻译】asp.net core中使用FluentValidation来进行模型验证
asp.net core中使用FluentValidation FluentValidation 可以集成到asp.net core中.一旦启用,MVC会在通过模型绑定将参数传入控制器的方法上时使用F ...
- 在.NET Core 中使用 FluentValidation 进行规则验证
不用说,规则验证很重要,无效的参数,可能会导致程序的异常. 如果使用Web API或MVC页面,那么可能习惯了自带的规则验证,我们的控制器很干净: public class User { [Requi ...
- .NetCore MVC中的路由(2)在路由中使用约束
p { margin-bottom: 0.25cm; direction: ltr; color: #000000; line-height: 120%; orphans: 2; widows: 2 ...
随机推荐
- BZOJ3362 [Usaco2004 Feb]Navigation Nightmare 导航噩梦
标题效果:自脑补. 思维:与维护两个维度和可设置为检查右. 注意,标题给予一堆关系的.我们应该加入两对关系. Code: #include <cstdio> #include <cs ...
- C/C++综合測试题(三)
又刷了一套题 这些题都是百度.阿里巴巴.腾讯.网易.新浪等公司的面试原题,有一定的难度.只是确实相当有水平,能够通过做题来查漏补缺. 1.补充以下函数代码: 假设两段内存重叠,用memcpy函数可能会 ...
- 原代码,反码,解释和具体的补充 Java在>>和>>>差异
前两天分析 HashMap 的 hash 算法的时间,会见 >> 和 >>> 这两个符号.然后检查以下信息,我脑子里在某一时刻.今天遇到,我没想到居然忘 0-0.... ...
- Java重写round()方法
题目:完毕这种方法的代码实现 public static String round (String arg1, int arg2) 參数 arg1:表示等待被处理的数据:如:"100.286 ...
- 为了圣像画系统V1.0Beta版(javascript)-GIS520社区
地图标绘系统V1.0測试版 (界面比較难看,之后再统一美化!) 演示地址:http://www.gis520.com/gis/plotdemo/index.html 查看可在菜单Map--> ...
- K60 启动过程分析
很高兴老师借给我一K60的开发板,趁着暑假好好鼓捣鼓捣! 有了上图的过程分析我想心里大概有个低了吧! 以下看代码: /* CodeWarrior ARM Runtime Support Library ...
- 【2014 Multi-University Training Contest 2 1002】/【HDU 4873】 ZCC Loves Intersection
果然,或滥用零件,啥都不说了.我们欣慰地学习阅读.这两天残疾儿童是数学. 这是求所需的问题,不明确.贴上官方的解题报告. watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi ...
- linux 字符界面浏览器 w3m(转)
最近找到了几个linux终端下使用的浏览器,主要用来测试本机web服务器是否搭建成功.因为我们一般是用ssh客户端连接linux的,所以很需要一个字符界面的浏览器.找了几个显示都不理想,只有w3m用起 ...
- 在 Windows Server 2008 R2 上安装 IIS 7.5
原文 在 Windows Server 2008 R2 上安装 IIS 7.5 默认情况下,Windows Server(R) 2008 R2 上不安装 IIS 7.5.可以使用服务器管理器中的“添加 ...
- Angular绑定数据时转义html标签
AngularJs在绑定数据时默认会以文本的形式出现在页面上,比如我现在有这样一段代码 <div ng-controller="testCtrl">{{data}}&l ...