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验证实体相关推荐

  1. ASP.NET MVC中的身份验证

    传统的登录验证方式,是通过将用户的登录状态信息保存在服务端的Session中,再利用客户端浏览器的Cookie保存SessionID,这样浏览器每次在向服务端发起请求时,都会携带该Cookie值,服务 ...

  2. asp.net mvc中的后台验证

    asp.net mvc的验证包含后台验证和前端验证.后台验证主要通过数据注解的形式实现对model中属性的验证,其验证过程发生在model绑定的过程中.前端验证是通过结合jquery.validate ...

  3. asp.net MVC 中使用dataannotation验证Model

    看到的一个好文章,讲如何验证Model webconfig中添加 <appSettings>         <add key="ClientValidationEnabl ...

  4. asp.net MVC 中 Session统一验证的方法

    验证登录状态的方法有:1  进程外Session   2 方法过滤器(建一个类继承ActionFilterAttribute)然后给需要验证的方法或控制器加特性标签 3 :新建一个BaseContro ...

  5. ASP.NET MVC如何实现自定义验证(服务端验证+客户端验证)

    ASP.NET MVC通过Model验证帮助我们很容易的实现对数据的验证,在默认的情况下,基于ValidationAttribute的声明是验证被使用,我们只需要将相应的ValidationAttri ...

  6. 在Asp.Net MVC中实现RequiredIf标签对Model中的属性进行验证

    在Asp.Net MVC中可以用继承ValidationAttribute的方式,自定制实现RequiredIf标签对Model中的属性进行验证 具体场景为:某一属性是否允许为null的验证,要根据另 ...

  7. ASP.NET Core MVC 中的模型验证

    数据模型的验证被视为是数据合法性的第一步,要求满足类型.长度.校验等规则,有了MVC的模型校验能够省却很多前后端代码,为代码的简洁性也做出了不少贡献. 原文地址:https://docs.micros ...

  8. 如何在 ASP.NET MVC 中集成 AngularJS(3)

    今天来为大家介绍如何在 ASP.NET MVC 中集成 AngularJS 的最后一部分内容. 调试路由表 - HTML 缓存清除 就在我以为示例应用程序完成之后,我意识到,我必须提供两个版本的路由表 ...

  9. 如何在 ASP.NET MVC 中集成 AngularJS

    介绍 当涉及到计算机软件的开发时,我想运用所有的最新技术.例如,前端使用最新的 JavaScript 技术,服务器端使用最新的基于 REST 的 Web API 服务.另外,还有最新的数据库技术.最新 ...

最新文章

  1. android Unable to add window -- token null is n...
  2. 深入探索C++对象模型学习笔记
  3. 【收藏】docker安装redis
  4. setTimeout那些事儿
  5. SQL Server执行计划
  6. java gui 层次结构_JAVA GUI学习 - JTree树结构组件学习 ***
  7. 进行连续心率监测可以诊断哪些疾病?
  8. 在cad如果用计算机,CAD如何使用快速计算器为中的变量区域功能
  9. H5使用OCR身份证识别
  10. modbus-tcp协议通过Java代码获取从机数据
  11. 基于FPGA的关于flash一些学习记录
  12. 机器视觉中偏振片的应用
  13. JAVA制作QQ空间点赞_利用Javascript实现QQ空间自动点赞
  14. SVN工具介绍- VisualSVN Server与TortoiseSVN
  15. linux查看进程的代码,Linux ps 查看进程(示例代码)
  16. 机器学习小白入门--统计学知识 Z-Value for Proportions
  17. mysql建立数据库并给定别名_MySQL数据库基本操作(四)
  18. 国内嵌入式工程师薪酬TOP30公司
  19. 深度剖析不同企业类型私域运营的方法
  20. VC++MFC应用程序向导

热门文章

  1. DCMTK:使用dcmimage 库将DICOM图像转换为PPM或PGM
  2. OpenCV测量视频编码和解码的性能(附完整代码)
  3. WebAssembly的Qt
  4. C++Poisso statistics泊松统计的实现算法(附完整源码)
  5. 右值引用和move语义?
  6. C++实现归并排序(附完整源码)
  7. QT的QSGSimpleMaterialShader类的使用
  8. java recv failed,jmeter压测报错Unrecognized Windows Sockets error: 0: recv failed
  9. ecs要按两次才有效_猫咪想要增肥有什么办法?吃是最简单有效的了,但要吃对了才行...
  10. php手机接口购物车怎么实现,php购物车的实现原理