在 .NET Core 中使用 FluentValidation 進行驗證

一、從 NuGet 安裝 FluentValidation

使用 FluentValidation 時,核心的包時 FluentValidationFluentValidation.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>();


參考文檔

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章