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()
.When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address)
.NotEmpty()
.WithMessage("地址不能为空")
.Length(, )
.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()));
}
}
}

  

最新文章

  1. 详解CSS的相对定位和绝对定位
  2. Mobile Web中URL设计问题
  3. 【树莓派】 Failed to fetch http://mirrordirector.raspbian.org/raspbian/pool/main/c/chkconfig/chkconfig_11.4.54.60.1debian1_all.deb Could not resolve &#39;mirrordirector.raspbian.org&#39;
  4. MFC中输入框的文本转换为char[]字符数组类型
  5. eclipse编辑器配置
  6. redis+crontab+php异步处理任务
  7. 在FireFox中安装Selenium IDE
  8. Oracle中instr 函数的详解
  9. pybombs 安装
  10. Asp.net文件缓存依赖
  11. history对象的使用--JavaScript基础
  12. 【转】forbids in-class initialization of non-const static member不能在类内初始化非const static成员
  13. Codeforces Round #428 (Div. 2) D. Winter is here 容斥
  14. luogu3203 弹飞绵羊 (LCT)
  15. AngularJS的增删改查、state嵌套案例,不涉及服务端
  16. elasticsearch term match multi_match区别
  17. 关于&quot;undefined reference&quot;错误
  18. Angular CLI 安装和使用以及安装失败的解决方法
  19. PHP生成缩略图(1)--简单缩略图
  20. Hadoop到底能做什么?怎么用hadoop?

热门文章

  1. C代码工具--自动生成enum值和名字映射代码
  2. Winodow Server Backup学习向导-window 2008
  3. Windows服务器安装配置PHP7.0环境图文教程
  4. SAP HANA专题分析目录
  5. windows下安装iReport 并确保启动正确
  6. 【转】windows消息和消息队列详解
  7. (转载)JAVA敏捷开发环境搭建
  8. slot游戏中的数学概念
  9. gulp插件(gulp-jmbuild),用于WEB前端构建
  10. 作业七:团队项目——Alpha版本冲刺阶段-12