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 ...
随机推荐
- 惠普4431s 笔记本配置
hp-4431s驱动精灵硬件检测报告 版本:2015.3.26.1363(8.1.326.1363)================================================== ...
- jQuery整理笔记9----函数形式发展
在一些照片中使用演示样本.插入.样式文件下载:点我进入下载 过去在开发过程中关于table方面的jquery应用不过局限于使用jquery操作table添加一行.删除一列等等操作.今天整理的跟过去用的 ...
- 【转】[Android实例] Handler+ExecutorService(线程池)+MessageQueue模式+缓存模式
android线程池的理解,晚上在家无事 预习了一下android异步加载的例子,也学习到了一个很重要的东东 那就是线程池+缓存 下面看他们的理解. [size=1.8em]Handler+Runn ...
- 处理FTP上传成功推理
#登录FTPserver获取指定文件 #$1:server住址 #$2:帐户 #$3:password #$4:文件路径名 #$5:本地文件路径名 #$6:本地文件名 #比量ftp上传结果: #获取上 ...
- VIM
初步
按i前插入字符.a在光标后追加字符 ctrl+d将光标下称半个窗体.按Ctrl+u将光标上移半个窗体 在输入模式下:ctrl+h删除字符,ctrl+u删除行.ctrl+w删除字 命令模式下.x删除字符 ...
- 使用shell命令分析统计日志
用户需要登录统计信息,当分析用户行为,使用shell通常可以很容易地取出了大量的数据.删除,然后放入excel统计. 例如:统计日志含有loadCustomProcess这个地址的訪问,按訪问耗时排序 ...
- C# - Abstract Classes
Abstract classes are closely related to interfaces. They are classes that cannot be instantiated, ...
- Android发展Singleton模式
这是什么Singleton模式?它是Java23之间的一种模式,在Android发展也有着广泛的应用,例Calander类别,当对象是由未创建 new Calander而是Calander.getIn ...
- php用魔术方法__call实现类函数重载
因为php是弱类型语言,不喜欢c++通过改变函数返回相同的值键入的参数的数目和功能将过载!但在需求函数的实际发展可能过载.开发需求,我们能够通过魔术方法__call()来实现函数重载. class T ...
- Eclipse正在使用Ant扑灭Android数据包错误的解决方案 – Perhaps JAVA_HOME does not point to the JDK
问题描写叙述: 在Eclipse中执行ant批量打包工具出错,日志信息例如以下: D:\Android\android-sdk-windows\tools\ant\build.xml:601: The ...