zoukankan      html  css  js  c++  java
  • 使用FluentValidation来进行数据有效性验证

    之前我介绍过了使用系统自带的Data Annotations来进行数据有效性验证,今天在CodePlex上逛的时候,发现了一个非常简洁好用的库:FluentValidation

    由于非常简洁,就直接拿官网的例子演示了: 

        using FluentValidation;
    
        public class CustomerValidator : AbstractValidator<Customer>
        {
            public CustomerValidator()
            {
                RuleFor(customer => customer.Surname).NotEmpty();
                RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
                RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
                RuleFor(customer => customer.Address).Length(20, 250);
                RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
            }
    
            private bool BeAValidPostcode(string postcode)
            {
                // custom postcode validating logic goes here
            }
        }
    
        Customer customer = new Customer();
        CustomerValidator validator = new CustomerValidator();
        ValidationResult results = validator.Validate(customer);
    
        bool validationSucceeded = results.IsValid;
        IList<ValidationFailure> failures = results.Errors;

    它还可以非常方便的与Asp.Net集成,用起来非常方便。官网的帮助文档也非常详尽,有数据有效性检验的朋友赶紧用起来把。

  • 相关阅读:
    php设计模式 — 简单工厂模式(静态工厂方法模式)
    Vue-Router
    各种选项卡
    jq动画
    如何使用swiper写轮播
    Gulp代码压缩
    闭包
    jquery.validation校验
    grunt-js文件压缩
    CSS
  • 原文地址:https://www.cnblogs.com/TianFang/p/3777060.html
Copyright © 2011-2022 走看看