尘叶心繁

.net Core FluentValidation 验证框架

电脑版发表于:2019/10/28 16:46


1.前言 (功能与特点)


功能:

    验证字段的属性大小

特点:

  1.     验证逻辑与业务逻辑分离

  2.     灵活,功能强大 (使用Fluent API,Lambda表达式)


官网地址:https://fluentvalidation.net/


2.安装 FluentValidation 相关工具包



3.案例

通过PostResourceValidator.cs类验证PostResource.cs


PostResourceValidator.cs Code:

public class PostResourceValidator:AbstractValidator<PostResource>
{
    public PostResourceValidator()
    {
            //PropertyName表示字段名
        RuleFor(x => x.Author)
            .NotNull()
            .WithName("作者")
            .WithMessage("{PropertyName}是必填的")
            .MaximumLength(50)
            .WithMessage("{PropertyName}的最大长度是{MaxLength}");
    }
}

PostResource.cs Code:

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; }
}

Startup.cs 中 ConfigureServices 方法

services.AddTransient<IValidator<PostResource>, PostResourceValidator>();


这样所有验证都会去 PostResourceValidator.cs 类里面过一遍验证


后续更新....

关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢