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

NET MVC中使用FluentValidation的更多相关文章

  1. ASP.NET MVC中使用FluentValidation验证实体

    1.FluentValidation介绍 FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的 ...

  2. ASP.NET MVC中使用FluentValidation验证实体(转载)

    1.FluentValidation介绍 FluentValidation是与ASP.NET DataAnnotataion Attribute验证实体不同的数据验证组件,提供了将实体与验证分离开来的 ...

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

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

  4. 如何在 ASP.NET MVC 中集成 AngularJS(1)

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

  5. MVC 中集成 AngularJS1

    在 ASP.NET MVC 中集成 AngularJS(1)   介绍 当涉及到计算机软件的开发时,我想运用所有的最新技术.例如,前端使用最新的 JavaScript 技术,服务器端使用最新的基于 R ...

  6. ASP.NET Core WebApi中使用FluentValidation验证数据模型

    原文链接:Common features in ASP.NET Core 2.1 WebApi: Validation 作者:Anthony Giretti 译者:Lamond Lu 介绍 验证用户输 ...

  7. 【翻译】asp.net core中使用FluentValidation来进行模型验证

    asp.net core中使用FluentValidation FluentValidation 可以集成到asp.net core中.一旦启用,MVC会在通过模型绑定将参数传入控制器的方法上时使用F ...

  8. 在.NET Core 中使用 FluentValidation 进行规则验证

    不用说,规则验证很重要,无效的参数,可能会导致程序的异常. 如果使用Web API或MVC页面,那么可能习惯了自带的规则验证,我们的控制器很干净: public class User { [Requi ...

  9. .NetCore MVC中的路由(2)在路由中使用约束

    p { margin-bottom: 0.25cm; direction: ltr; color: #000000; line-height: 120%; orphans: 2; widows: 2 ...

随机推荐

  1. tcpdump参数及使用介绍(转)

    原文地址:http://dogdogcom.blog.51cto.com/2402458/490398 tcpdump -a 将网络地址和广播地址转变成名字: -d 将匹配信息包的代码以人们可以理解的 ...

  2. jq实现图像旋转木马:轮焦点+关于控制+自己主动旋转木马

    资源:http://www.ido321.com/862.html html代码: 1: <!DOCTYPE html> 2: <html lang="en"&g ...

  3. WdatePicker日期不能弹出框

    发育.在引用WdatePicker当日历控件,正确的路径.日历控件封装完整,在正常情况下的代码,调试正常,但公告日期后不能弹出框,最终核实后想办法找到一个解决方案: 更改方法:于WdatePicker ...

  4. Netty In Action中文版 - 第一章:Netty介绍

    本章介绍 Netty介绍 为什么要使用non-blocking IO(NIO) 堵塞IO(blocking IO)和非堵塞IO(non-blocking IO)对照 Java NIO的问题和在Nett ...

  5. PHP于DIRECTORY_SEPARATOR任务

    DIRECTORY_SEPARATOR是php的内部常量.用于显示系统分隔符的命令,不须要不论什么定义与包括就可以直接使用. 在windows下路径分隔符是\(当然/在部分系统上也是能够正常执行的), ...

  6. SQL Server 2008性能故障排查(三)——I/O

    原文:SQL Server 2008性能故障排查(三)--I/O 接着上一章:CPU瓶颈 I/O瓶颈(I/O Bottlenecks): SQLServer的性能严重依赖I/O子系统.除非你的数据库完 ...

  7. ExtJS学习笔记:定义extjs类别

    类的定义 Ext.define('Cookbook.Vehicle', { Manufacturer: 'Aston Martin', Model: 'Vanquish', getDetails: f ...

  8. 深入浅出jsonp(转)

    前言 第一次听说jsonp,其实早在2年之前.当时在做一个活动页面的抽奖模块,要从服务端get一个概率,当时什么都不懂,同事说用ajax,我就用ajax,同事说dataType改成jsonp,我就改成 ...

  9. NOI第一天感想&小结

    嘛...中午总算是到了深圳了--在虹桥机场和飞机上和市队大神们一起讨论各种各样奇(sang)葩(bing)的算(ren)法(lei)还是非常开心的,在此再各种膜拜一下尽管没来比赛的FFT大神@陈中瑞 ...

  10. imagick获取图片的大小bug

    <? php /* imagick的获取图片的高度和宽度函数有问题,使用GD函数可获得正确结果 gd函数 array getimagesize ( string $filename [, arr ...