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()
.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()));
}
}
}
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的责任就是负责信息访问与商业逻辑验证的,所以我们把验证逻辑加 ...
- 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 ...
- NET MVC中使用FluentValidation
ASP.NET MVC中使用FluentValidation验证实体 1.FluentValidation介绍 FluentValidation是与ASP.NET DataAnnotataion ...
- ASP.NET MVC如何实现自定义验证(服务端验证+客户端验证)
ASP.NET MVC通过Model验证帮助我们很容易的实现对数据的验证,在默认的情况下,基于ValidationAttribute的声明是验证被使用,我们只需 要将相应的ValidationAttr ...
- ASP.NET MVC中商品模块小样
在前面的几篇文章中,已经在控制台和界面实现了属性值的笛卡尔乘积,这是商品模块中的一个难点.本篇就来实现在ASP.NET MVC4下商品模块的一个小样.与本篇相关的文章包括: 1.ASP.NET MVC ...
随机推荐
- Creating a ClickOnce application
refer to http://www.youtube.com/watch?v=t4BTLdIMYEY
- 非对称加密RSA的应用及在C#中的实现
quote: http://www.cnblogs.com/happinessCodes/archive/2010/07/27/1786404.html 一说到数据的加密,常常会涉及到这几个单词: ...
- iOS 标题内容待定
UITableView: UITableViewCell的声明文件.所包含的: UIView控件(contentView,作为其它元素的父控件) -- 容器 两个UILabel控件( textLabe ...
- Linux内核--网络栈实现分析(二)--数据包的传递过程(上)
本文分析基于Linux Kernel 1.2.13 原创作品,转载请标明http://blog.csdn.net/yming0221/article/details/7492423 更多请看专栏,地址 ...
- React Native也正式发布了
var React = require('react-native'); var { TabBarIOS, NavigatorIOS } = React; var App = React.create ...
- vc编译 curl 7.36.0
CURL邮件列表中提到官方最新版本的windows devel包中缺少文件,而我又用不到https,所以我就自己下载源码包来编译了 下载源码包:http://curl.haxx.se/download ...
- Asp.Net Web API 2第十课——使用OWIN自承载Web API
详情请查看http://aehyok.com/Blog/Detail/71.html 个人网站地址:aehyok.com QQ 技术群号:206058845,验证码为:aehyok 本文文章链接:ht ...
- guava之Joiner 和 Splitter
最近在给客户准备一个Guava的分享,所以会陆续的更新关于Guava更多的细节分享.本文将记录Guava中得字符串处理Joiner(连接)和Splitter(分割)处理. Joiner 首先我们来看看 ...
- nim的引用和指针
nim语言的引用和其他语言的指针有点相似 可以提供一种“多对一”的关系 这就意味着不同的引用可以指向同一个内存位置 nim区分可被追踪的引用和不可被追踪的引用 不可被追踪的引用又称为指针 可被追踪的引 ...
- web前端工程师在移动互联网时代里的地位问题
支付宝十周年推出了一个新产品:支付宝的十年账单,我也赶个时髦查看了一下我的支付宝十年账单,哎,感慨自己真是太屌丝了,不过这只是说明我使用淘宝少了,当我大规模网上购物时候,我很讨厌慢速的快递,所以我大部 ...