在 .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>();


参考文档

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