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()));
}
}
}

ASP.NET MVC中使用FluentValidation验证实体(转载)的更多相关文章
- ASP.NET MVC中使用FluentValidation验证实体
1.FluentValidation介绍 FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的 ...
- ASP.NET MVC中使用窗体验证出现上下文的模型在数据库创建后发生更改,导致调试失败(一)
在ASP.NET MVC中使用窗体验证.(首先要明白,验证逻辑是应该加在Model.View和Controller哪一个里面?由于Model的责任就是负责信息访问与商业逻辑验证的,所以我们把验证逻辑加 ...
- windows server 证书的颁发与IIS证书的使用 Dapper入门使用,代替你的DbSQLhelper Asp.Net MVC中Action跳转(转载)
windows server 证书的颁发与IIS证书的使用 最近工作业务要是用服务器证书验证,在这里记录下一. 1.添加服务器角色 [证书服务] 2.一路下一步直到证书服务安装完成; 3.选择圈选 ...
- C# MVC 用户登录状态判断 【C#】list 去重(转载) js 日期格式转换(转载) C#日期转换(转载) Nullable<System.DateTime>日期格式转换 (转载) Asp.Net MVC中Action跳转(转载)
C# MVC 用户登录状态判断 来源:https://www.cnblogs.com/cherryzhou/p/4978342.html 在Filters文件夹下添加一个类Authenticati ...
- asp.net mvc 中的自定义验证(Custom Validation Attribute)
前言
- asp.net mvc中的后台验证
asp.net mvc的验证包含后台验证和前端验证.后台验证主要通过数据注解的形式实现对model中属性的验证,其验证过程发生在model绑定的过程中.前端验证是通过结合jquery.validate ...
- 再议ASP.NET MVC中CheckBoxList的验证
在ASP.NET MVC 4中谈到CheckBoxList,经常是与CheckBoxList的显示以及验证有关.我在"MVC扩展生成CheckBoxList并水平排列"中通过扩展H ...
- asp.net MVC 中 Session统一验证的方法
验证登录状态的方法有:1 进程外Session 2 方法过滤器(建一个类继承ActionFilterAttribute)然后给需要验证的方法或控制器加特性标签 3 :新建一个BaseContro ...
- Asp.Net MVC中Action跳转(转载)
首先action的跳转大致归类: 1跳转到与当前同一控制器内的action和不同控制器内的action. 2带有参数的action跳转和不带参数的action跳转. 3跳转到指定视图,不经过Contr ...
随机推荐
- ionic中android的返回键
ionic中android的返回键 在ionic框架中已经注册了几个返回事件,分别是 view sideMenu modal actionSheet popup loading 他们的优先级分别是 v ...
- 分析技术和方法论营销理论知识框架,营销方面4P、用户使用行为、STP,管理方面5W2H、逻辑树、金字塔、生命周期
原文:五种分析框架:PEST.5W2H.逻辑树.4P.用户使用行为 最近在一点点的啃<谁说菜鸟不懂得数据分析>,相当慢,相当的费脑力,总之,真正的学习伴随着痛苦:) 最初拿到这本书的时候, ...
- repo命令详解
Android 为企业提供一个新的市场,无论大企业,小企业都是处于同一个起跑线上.研究 Android 尤其是 Android 系统核心或者是驱动的开发,首先需要做的就是本地克隆建立一套 Androi ...
- windows 上搭建gitblit
https://www.cnblogs.com/ucos/p/3924720.htmlhttps://www.cnblogs.com/sumuncle/p/6362697.htmlhttp://www ...
- [转]Mybatis foreach 批量操作
原文地址:https://blog.csdn.net/jason5186/article/details/40896043 foreach属性属性 描述item 循环体中的具体对象.支持属 ...
- 使用C#的Conditional特性与Unity编辑器宏命令做条件编译
概要 在传统的C#项目中,用Conditional特性做条件编译时,需要在Visual Studio中项目的属性里添加上条件编译符号,用法参考这篇文章. 而在Unity项目中,条件编译符号需要在Uni ...
- yml 后面的配置覆盖前面的
事情是这样的: a: b: c: tomcat d: hoho # 中间还隔了好多 a: b: c: tomcat 这种情况下,后面的配置会覆盖前面的所有配置,即 a.d = hoho 也会被覆盖 y ...
- Laravel-mix 中文文档
镜像地址 : https://segmentfault.com/a/1190000015049847原文地址: Laravel Mix Docs 概览 基本示例 larave-mix 是位于w ...
- 微软消息队列-MicroSoft Message Queue(MSMQ)队列的C#使用
目录 定义的接口 接口实现 建立队列工厂 写入队列 获取消息 什么是MSMQ Message Queuing(MSMQ) 是微软开发的消息中间件,可应用于程序内部或程序之间的异步通信.主要的机制是:消 ...
- java Illegal unquoted character ((CTRL-CHAR, code X)): has to be escaped using backslash to be included in string value
今天在同步日志到ES的时候出现转换Json后 存到es中报这个错. Illegal unquoted character ((CTRL-CHAR, code X)): has to be escape ...