ASP.NET MVC5驗證系列之Fluent Validation_實用技巧

來源:互聯網
上載者:User

前面兩篇文章學習到了,服務端驗證,和用戶端的驗證,但大家有沒有發現,這兩種驗證各自都有弊端,伺服器端的驗證,驗證的邏輯和代碼的邏輯混合在一起了,如果代碼量很大的話,以後維護擴充起來,就不是很方便。而用戶端的驗證,必須要啟用用戶端驗證,也就是在設定檔中配置相應的節點,並且還要引入Jquery外掛程式。如果人為的在瀏覽器上,禁用了js指令碼,那麼用戶端驗證就不起作用了,所以在這裡,我將繼續學習另外一個驗證,也就是Fluent Validation。

Fluent Validation是一個開源的.NET類庫,它使用Fluent介面和lambda運算式,來為實體做驗證。Fluent Validation是專門為實體做驗證使用的。它的優點是:把驗證邏輯和你代碼的商務邏輯分別開了。這就是AOP的思想。就是橫切關注點。你只需要關注某一個模組。這樣就保證了代碼的純潔度。

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.
面向方面程式設計作為一種新的軟體開發範型,能夠實現橫切關注點的模組化,其特有的語言元素和功能為切片增加了難度。
好了,廢話太多,直接進入正題,
首先我們建立一個空白的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);  } }}
 

修改一下,預設的路由:

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輸入非法的資料

輸入合法的資料:

這裡就完成了Fluent Validation驗證。大家可以看到,這樣的驗證是不是乾淨簡潔多了,配置資訊都在一個類中,方便維護和擴充。不想資料註解那樣,把驗證資訊和實體混合了。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.