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中使用Knockout實踐05,基本驗證ASP.NETMVC
- 在ASP.NET MVC中使用Knockout實踐06,自定義驗證、非同步驗證ASP.NETMVC非同步
- Asp.Net MVC 身份驗證-FormsASP.NETMVCORM
- ASP.NET MVC驗證碼演示ASP.NETMVC
- Asp.net MVC中表單驗證ASP.NETMVC
- asp.net mvc中的使用者登入驗證過濾器ASP.NETMVC過濾器
- MVC學習筆記之:ASP.NET MVC的客戶端驗證-jQuery.validate驗證結合Model驗證中的實現MVC筆記ASP.NET客戶端jQuery
- ASP.NET MVC之初體驗ASP.NETMVC
- MVC驗證09-使用MVC的Ajax.BeginForm方法實現非同步驗證MVCORM非同步
- [ASP.NET MVC 小牛之路]16 - Model 驗證ASP.NETMVC
- ASP.NET MVC學習之模型驗證篇ASP.NETMVC模型
- ASP.NET MVC許可權驗證 封裝類ASP.NETMVC封裝
- 在ASP.NET MVC中使用Knockout實踐07,自定義驗證資訊的位置與內容ASP.NETMVC
- MVC3中使用驗證介面卡修改預設的驗證提示資訊MVC
- ASP.NET MVC中簡單使用AutofacASP.NETMVC
- Asp.Net Mvc後臺資料驗證自測小DemoASP.NETMVC
- MVC驗證08-jQuery非同步驗證MVCjQuery非同步
- asp.net 角色身份驗證的使用ASP.NET
- Asp.net中基於Forms驗證的角色驗證授權ASP.NETORM
- MVC驗證11-對複雜型別使用jQuery非同步驗證MVC型別jQuery非同步
- spring mvc實現登入驗證碼SpringMVC
- ASP.NET MVC結合jQuery外掛進行資料驗證ASP.NETMVCjQuery
- 【Hover】ASP.Net實現驗證碼!ASP.NET
- MVC驗證01-基礎、遠端驗證MVC
- MVC驗證02-自定義驗證規則、郵件驗證MVC
- 也談Asp.net 中的身份驗證ASP.NET
- Asp.Net 中使用HttpModule 做Session驗證ASP.NETHTTPSession
- ASP.NET驗證控制元件的使用ASP.NET控制元件
- MVC驗證04-自定義驗證規則、日期範圍驗證MVC
- Asp.Net MVC 使用 AjaxASP.NETMVC
- MVC驗證07-自定義Model級別驗證MVC
- MVC Remote 伺服器驗證MVCREM伺服器
- MVC 後設資料驗證MVC
- Asp.Net Mvc使用Autofac實現依賴注入ASP.NETMVC依賴注入
- ASP.NET MVC 5改進了基於過濾器的身份驗證ASP.NETMVC過濾器
- Asp.net(C#)實現驗證碼功能ASP.NETC#
- Asp.net MVC中ViewData與ViewBag的使用方法ASP.NETMVCView
- ASP.NET MVC中URL末尾斜槓的實現ASP.NETMVC