從 NuGet 安裝 FluentValidation
使用 FluentValidation 時,核心的包時 FluentValidation 和 FluentValidation.AspNetCore。
使用 NuGet 包管理控制台運行以下命令進行安裝:
Install-Package FluentValidation
Install-Package FluentValidation.AspNetCore
爭對 Resource類 建立 FluentValidation
首先以下是 Resource類:
public class PostResource
{
public int Id { get; set; }
public string Title { get; set; }
public string Body { get; set; }
public string Author { get; set; }
public DateTime UpdateTime { get; set; }
public string Remark { get; set; }
}
以下是對 PostResource 建立驗證示例:
// 需要繼承於 AbstractValidator<T> ,T 表示要驗證的類
public class PostResourceValidator : AbstractValidator<PostResource>
{
public PostResourceValidator() {
// 配置 Author
RuleFor(x => x.Author)
.NotNull() //不能為空
.WithName("作者")
//.WithMessage("required|{PropertyName}是必填的")
.WithMessage("{PropertyName}是必填的")
.MaximumLength(50)
//.WithMessage("maxlength|{PropertyName}的最大長度是{MaxLength}")
.WithMessage("{PropertyName}的最大長度是{MaxLength}");
// 配置 Body
RuleFor(x => x.Body)
.NotNull()
.WithName("正文")
.WithMessage("required|{{PropertyName}是必填的")
.MinimumLength(100)
.WithMessage("minlength|{PropertyName}的最小長度是{MinLength}");
}
}
在Startup中對寫好的驗證進行注冊
在Startup類的ConfigureServices方法中進行注冊
//services.AddTransient<IValidator<ResourceModel>, 驗證器>();
services.AddTransient<IValidator<PostResource>, PostResourceValidator>();
- 參考文檔: