• 关于简单的 FluentValidation 验证


    FluentValidation :  https://github.com/JeremySkinner/FluentValidation

    关于为何要使用,因为微软自带的模型验证有点弱,还需要自己去写一大堆的验证。

    关于asp.net core的集成 我用的是 FluentValidation.AspNetCore  nuget

    直接在addmvc后添加 AddFluentValidation() 就好了 

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddFluentValidation();

    我一般用反射注入msdi 

      // 注册 Validator 
                    var types = assembly.GetTypes().Where(p =>
                        p.BaseType != null && p.BaseType.GetInterfaces().Any(x => x == typeof(IValidator)));
                    foreach (var type in types)
                    {
                        if (type.BaseType != null)
                        {
                            var genericType = typeof(IValidator<>).MakeGenericType(type.BaseType.GenericTypeArguments[0]);
                            services.AddTransient(genericType, type);
                        }
                    }

    然后这里例举一些比较常用的方法 

    以下是我的模型 。

     public class UserInput
        {
            public string CustomerId { get; set; }
            public string UserName { get; set; }
            public string PhoneNumber { get; set; }
            public string FullName { get; set; }
            public string Description { get; set; }
            public string UnionId { get; set; }
            public string Email { get; set; }
            public string Password { get; set; }
        }

    这里是我的validator

    public class UserInputVaildator : AbstractValidator<UserInput>
        {
            public UserInputVaildator()
            {
                RuleFor(m => m.UserName).NotEmpty().WithMessage("登录名是必须的");
    
                RuleFor(m => m.CustomerId).NotEmpty().WithMessage("客户Id是必须的");
                //当手机号为空的时候就不会再去验证手机号格式是否 因为默认是不会停止验证。
                RuleFor(m => m.PhoneNumber)
                    .Cascade(CascadeMode.StopOnFirstFailure)
                    .NotEmpty().WithMessage("手机号是必须的")
                    .PhoneNumber().WithMessage("手机格式不正确");
                //这里的意思是当 邮箱不为空时采取验证邮箱格式是否正确
                RuleFor(m => m.Email)
                    .EmailAddress().When(m => !string.IsNullOrWhiteSpace(m.Email)).WithMessage("邮箱格式不正确");
            }
        }

    当然,还有一些其他的东西  

       public class TestInput
        {
            public string Grant { get; set; }
    
            public int  Number { get; set; }
        }
    public class TestInputValidator : AbstractValidator<TestInput>
        {
            public TestInputValidator()
            {
           RuleSet(
    "test", () => { RuleFor(m => m.Number).GreaterThan(0).WithMessage("Number要大于0"); }); RuleFor(m => m.Grant).NotEmpty().WithMessage("Grant不能为空"); } }

     规则的设置,可以适应不同的验证场景,对同一个Model进行不同的验证

    [Route("api/[controller]")]
        [ApiController]
        public class TestController : ControllerBase
        {
            //
            [HttpGet]
            public IActionResult Get([FromQuery]TestInput input)
            {
                return Ok();
            }
    
            //规则的设置,可以适应不同的验证场景,对同一个Model进行不同的验证
            [HttpPost]
            public IActionResult Index([FromBody][CustomizeValidator(RuleSet = "test")]TestInput input)
            {
                return Ok("213");
            }
        }
        

    父类,接口的验证 

    public class CustomerCreateInput : ClientInput, ICustomerInput{
        //具体的实现接口
    }
    
    public class CustomerInputInterfaceValidator : AbstractValidator<ICustomerInput>{
      //具体 接口  验证逻辑
    }
    
    public class ClientInputVaildators : AbstractValidator<ClientInput>{
      //集体 基类 验证逻辑  
    }
    
    //那么我该如果重用接口和基类的验证逻辑
    public class CustomerCreateInputValidator : AbstractValidator<CustomerCreateInput>
        {
            public CustomerCreateInputValidator()
            {
                //只需要包含进来
                Include(new CustomerInputInterfaceValidator());
                Include(new ClientInputVaildators());
            }
        }

    这里就有个问题,如果包含的验证类中包含了 RuleSet,那么该如何启用。因为默认不会启用,这个问题,我也不知道 (~ ̄▽ ̄)~ 只能说我也不太精通,昨天刚刚开始用。
  • 相关阅读:
    vue--组件基础
    vue中的一些知识点--多看文档
    关于组件--React
    数组方法-->map()
    正则表达式使用
    border-image 和 border-color 不能同时使用问题
    gulp
    oninput 中文输入
    linux文档权限
    为什么使用 use strict
  • 原文地址:https://www.cnblogs.com/quan01994/p/11023424.html
Copyright © 2020-2023  润新知