ASP.NET MVC5驗證系列之Fluent Validation
前面兩篇文章學(xué)習(xí)到了,服務(wù)端驗證,和客戶端的驗證,但大家有沒有發(fā)現(xiàn),這兩種驗證各自都有弊端,服務(wù)器端的驗證,驗證的邏輯和代碼的邏輯混合在一起了,如果代碼量很大的話,以后維護(hù)擴展起來,就不是很方便。而客戶端的驗證,必須要啟用客戶端驗證,也就是在配置文件中配置相應(yīng)的節(jié)點,并且還要引入Jquery插件。如果人為的在瀏覽器上,禁用了js腳本,那么客戶端驗證就不起作用了,所以在這里,我將繼續(xù)學(xué)習(xí)另外一個驗證,也就是Fluent Validation。
Fluent Validation是一個開源的.NET類庫,它使用Fluent接口和lambda表達(dá)式,來為實體做驗證。Fluent Validation是專門為實體做驗證使用的。它的優(yōu)點是:把驗證邏輯和你代碼的業(yè)務(wù)邏輯分別開了。這就是AOP的思想。就是橫切關(guān)注點。你只需要關(guān)注某一個模塊。這樣就保證了代碼的純潔度。
Fluent Validation開源地址:https://github.com/JeremySkinner/fluentvalidation
例句:
Aspect-oriented program is a new software development paradigm that enables modular implementation of cross-cutting concerns,and poses difficulties for slicing of aspect-oriented programs.
面向方面程序設(shè)計作為一種新的軟件開發(fā)范型,能夠?qū)崿F(xiàn)橫切關(guān)注點的模塊化,其特有的語言元素和功能為切片增加了難度。
好了,廢話太多,直接進(jìn)入正題,
首先我們新建一個空白的MVC項目:在Model文件夾下新建一個類Customer:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Server_Side_Validation_IN_MVC.Models
{
public class Customer
{
public string Name { get; set; }
public string Email { get; set; }
}
}
然后新建一個文件夾Validator,在里面添加一個類CustomerValidator

既然是要使用Fluent Validation,那么就是要引用它的類庫了。

CustomerValidator類中,繼承AbstractValidator抽象類,(PS:這里和EF中的Fluent API類似,EF中是繼承EntityTypeConfiguration類)
using FluentValidation;
using Server_Side_Validation_IN_MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Server_Side_Validation_IN_MVC.Validator
{
public class CustomerValidator:AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(s => s.Name).NotEmpty().WithMessage("名字不能為空");
RuleFor(s => s.Email).NotEmpty().WithMessage("電子郵件不能為空");
RuleFor(s => s.Email).EmailAddress().WithMessage("電子郵件格式不合法");
}
}
}
控制器中的代碼:
using FluentValidation.Results;
using Server_Side_Validation_IN_MVC.Models;
using Server_Side_Validation_IN_MVC.Validator;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Server_Side_Validation_IN_MVC.Controllers
{
public class CustomerController : Controller
{
// GET: Customer
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Customer model)
{
CustomerValidator validator = new CustomerValidator();
ValidationResult result = validator.Validate(model);
if (result.IsValid)
{
ViewBag.Name = model.Name;
ViewBag.Email = model.Email;
}
else
{
foreach (var item in result.Errors)
{
ModelState.AddModelError(item.PropertyName, item.ErrorMessage);
}
}
return View(model);
}
}
}
修改一下,默認(rèn)的路由:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Customer", action = "Index", id = UrlParameter.Optional }
);
}

什么都不輸入,直接點擊Create:

輸入Name,不輸入Email

輸入Name,Email輸入非法的數(shù)據(jù)

輸入合法的數(shù)據(jù):

這里就完成了Fluent Validation驗證。大家可以看到,這樣的驗證是不是干凈簡潔多了,配置信息都在一個類中,方便維護(hù)和擴展。不想數(shù)據(jù)注解那樣,把驗證信息和實體混合了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
利用AJAX與數(shù)據(jù)島實現(xiàn)無刷新綁定
利用AJAX與數(shù)據(jù)島實現(xiàn)無刷新綁定...2007-03-03
Visual Studio 2017 (VS 2017)離線安裝包制作方法
這篇文章主要為大家詳細(xì)介紹了Visual Studio 2017離線安裝包的制作方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-03-03
c# 操作符?? null coalescing operator
?? "null coalescing" operator 是c#新提供的一個操作符,這個操作符提供的功能是判斷左側(cè)的操作數(shù)是否是null,如果是則返回結(jié)果是右側(cè)的操作數(shù);非null則返回左側(cè)的操作數(shù)。2009-06-06
Asp.Net2.0權(quán)限樹中Checkbox的操作
Asp.Net2.0權(quán)限樹中Checkbox的操作...2006-09-09
WPF中button按鈕同時點擊多次觸發(fā)click解決方法
這篇文章主要為大家詳細(xì)介紹了WPF中button按鈕同時點擊多次觸發(fā)click的解決方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-04-04

