Fluentvalidation的基本使用
前言:
fluentvalidation用於構建強類型驗證規則的流行.NET庫。方便好用快捷省心!!!
本文按照官方文檔進行試驗,如果深(不)入(看)的(我)研(寫)究(的)請去官網:https://fluentvalidation.net/
相關包:
核心:FluentValidation
.net core:FluentValidation.AspNetCore
.net::FluentValidation.Mvc5/FluentValidation.WebApi
本文使用.net core所以只安裝FluentValidation.AspNetCore即可
模型與驗證器:
准備一個需要的模型:
public class Customer
{
public int Id { get; set; }
public string Surname { get; set; }
public string Forename { get; set; }
public decimal Discount { get; set; }
public string Address { get; set; }
}
創建驗證器,對驗證類進行驗證
public class CustomerValidation:AbstractValidator<Customer>
{
public CustomerValidation()
{
RuleFor(customer => customer.Surname)
//不為空
.NotNull()
//最小/最大長度
.MinimumLength(2)
.MaximumLength(10)
//錯誤提示信息
.WithMessage("姓名長度不符!");
}
}
要點:
- 必須繼承於AbstractValidator
- AbstractValidator<需要驗證的類>
- 在構造函數中添加驗證
- RuleFor是對某一個屬性添加驗證規則
配置
先上圖:
- AddFluentValidation必須在AddMvc之后
- 方法里面可以進行想要的配置,比如關掉自帶的驗證器
- 如果驗證器較多的話建議使用這種程序集注入的方式
當然還有另外一種注入方式只是比較麻煩,看圖:
這樣也是可以的,不過比較麻煩。。。
使用
開頭說了,這東西方便好用快捷省心,所以根本不需要在控制器中進行額外的使用,一切從簡!
結果:
驗證器中對Surname屬性進行了不為空&長度大於2&長度小於10的限制,那么來看結果:
當我們點擊提交:
看來是成功了!界面很丑,請不要吐槽。。。
自定義驗證過程:
以上如果有錯誤請各位斧正,謝謝你的閱讀~