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

参考文档:


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM