• 好用的验证框架FluentValidation(上)


     

      把数据错误扼杀在早期,那就是在数据的入口处,一般数据都是打包成一个实体的方式进传递,FluentValidation就以实体类为单位进行属性验证的集合。

    Install-Package FluentValidation

    下面看一个例子吧。

    实体类:

    public class Person
    {
        public int Id { get; set; }
        public DateTime Birthday { get; set; }
        public string IDCard { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public PersonAddress Address { get; set; }
        public string Tel { get; set; }
    }
    public class PersonAddress
    {
        public string Country { get; set; }
        public string Province { get; set; }
        public string City { get; set; }
        public string County { get; set; }
        public string Address { get; set; }
        public string Postcode { get; set; }
    }

    验证实体类:

    /// <summary>
    /// Person验证
    /// </summary>
    public class PersonValidator : AbstractValidator<Person>
    {
        public PersonValidator()
        {
            RuleFor(p => p.Name).NotNull();
            RuleFor(p => p.Email).NotNull().EmailAddress();
            RuleFor(p => p.Birthday).NotNull();
            RuleFor(p => p.IDCard)
                .NotNull()
                .When(p => (DateTime.Now > p.Birthday.AddYears(1)))
                .WithMessage(p => $"出生日期为{p.Birthday},现在时间为{DateTime.Now},大于一岁,CardID值必填!");
            RuleFor(p => p.Tel).NotNull().Matches(@"^(\d{3,4}-)?\d{6,8}$|^[1]+[3,4,5,8]+\d{9}$");
            RuleFor(p => p.Address).NotNull();
            RuleFor(p => p.Address).SetValidator(new PersonAddressValidator());
        }
    }
    /// <summary>
    /// Person Address验证
    /// </summary>
    public class PersonAddressValidator : AbstractValidator<PersonAddress>
    {
        public PersonAddressValidator()
        {
            RuleFor(a => a.Country).NotNull();
            RuleFor(a => a.Province).NotNull();
            RuleFor(a => a.City).NotNull();
            RuleFor(a => a.County).NotNull();
            RuleFor(a => a.Address).NotNull();
            RuleFor(a => a.Postcode).NotNull().Length(6);
        }
    }

    使用场景:

    class Program
    {
        static void Main(string[] args)
        {
            var person = new Person()
            {
                //少一位
                Tel = "1345346711",
                Name = "桂素伟",
                //格式错误
                Email = "axzxs2001#163.com",
                //设置生日,没有身份证
                Birthday = DateTime.Parse("2020-03-28 00:00:00"),
    
                Address = new PersonAddress()
                {
                    //邮编位数不对
                    Postcode = "12345"
                },
            };
            var validator = new PersonValidator();
            var results = validator.Validate(person);
            if (!results.IsValid)
            {
                foreach (var failure in results.Errors)
                {
                    Console.WriteLine("属性 " + failure.PropertyName + " 验证失败:" + failure.ErrorMessage);
                }
            }
            Console.WriteLine("--------------------------------------------------------------------");
            Console.WriteLine(results.ToString("\r\n"));
        }
    }

      FluentValidation有一个很赞的功能,就是验证某一属性时,可以用别的属性的值作为条件,组合实现验证,这样就能适应更多的业务逻辑验证场景。比如上例中的,只有大于一岁(Birthday)的人,身份证(IDCard)是必填项。当然FluentValidation不只这些功能,比如嵌套实体验证,组合验证规则等,都是很贴心的功能,期待大家尝试。

      想要更快更方便的了解相关知识,可以关注微信公众号 
     

     

  • 相关阅读:
    Mysql 导入CSV数据 语句 导入时出现乱码的解决方案
    有用的 Mongo命令行 db.currentOp() db.collection.find().explain()
    MySql Host is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts' 解决方法 -摘自网络
    MongoDB索引相关文章-摘自网络
    批量更新MongoDB的列。
    RabbitMQ 消费端 Client CPU 100%的解决办法
    php根据命令行参数生成配置文件
    php解释命令行的参数
    使用memcache对wordpress优化,提速
    python基础技巧综合训练题2
  • 原文地址:https://www.cnblogs.com/axzxs2001/p/15862888.html
Copyright © 2020-2023  润新知