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中的使用者登入驗證過濾器ASP.NETMVC過濾器
- 在.NET Core 中使用 FluentValidation 進行規則驗證
- .Net Core 使用 FluentValidation
- ASP.NET MVC技能體系圖ASP.NETMVC
- MVC Remote 伺服器驗證MVCREM伺服器
- 【ASP.NET Core】使用最熟悉的Session驗證方案ASP.NETSession
- ASP.NET MVC/Core表單提交後臺模型二級屬性驗證問題ASP.NETMVC模型
- ASP.NET登入驗證ASP.NET
- mvc中常見的屬性驗證MVC
- ASP.NET Core - 實現自定義WebApi模型驗證ASP.NETWebAPI模型
- 雙重保險——前端bootstrapValidator驗證+後臺MVC模型驗證前端bootMVC模型
- asp.net core mvc 管道之中介軟體ASP.NETMVC
- asp.net core3.1 實戰開發(驗證碼的封裝和使用)ASP.NET封裝
- 在ASP.NET Core MVC 2.2 中使用AutoMapperASP.NETMVCAPP
- Spring Security 6中使用PKCE實現身份驗證Spring
- ASP.NET MVC路由ASP.NETMVC路由
- gin使用BasicAuth()(驗證)中介軟體
- 在Keycloak中實現多租戶並在ASP.NET Core下進行驗證ASP.NET
- ASP.NET MVC下使用AngularJs語言(七):Cookie的使用ASP.NETMVCAngularJSCookie
- ASP.NET中HttpApplication中ProcessRequest方法中執行的事件順序;ASP.NET WebForm和MVC總體請求流程圖...ASP.NETHTTPAPP事件WebORMMVC流程圖
- 記一次ASP.NET MVC效能優化(實際專案中)ASP.NETMVC優化
- springboot中擴充套件ModelAndView實現asp.net core mvc的ActionResult效果Spring Boot套件ViewASP.NETMVC
- 使用 Spring Validator 介面實現驗證Spring
- ASP.NET MVC 反射例子ASP.NETMVC反射
- [Hei.Captcha] Asp.Net Core 跨平臺驗證碼實現APTASP.NET
- gRPC中整合asp.net identity實現oAuth認證RPCASP.NETIDEOAuth
- 身份驗證會影響使用者體驗嗎?
- Spring MVC之例項初體驗SpringMVC
- Rust中實現JWT身份驗證RustJWT
- Asp.Net Core 3.1 學習4、Web Api 中基於JWT的token驗證及Swagger使用ASP.NETWebAPIJWTSwagger
- ASP.NET MVC使用input標籤上傳檔案ASP.NETMVC
- 從 MVC 到使用 ASP.NET Core 6.0 的最小 APIMVCASP.NETAPI
- ASP.NET MVC & WebApi 中實現Cors來讓Ajax可以跨域訪問ASP.NETMVCWebAPICORS跨域
- asp.net core mvc 分頁ASP.NETMVC
- ASP.Net MVC過濾器ASP.NETMVC過濾器
- ASP.NET MVC – 安全簡介ASP.NETMVC
- ASP.NET MVC – 模型簡介ASP.NETMVC模型
- 將”ListControl”引入ASP.NET MVCASP.NETMVC