使用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集成,用起来非常方便。官网的帮助文档也非常详尽,有数据有效性检验的朋友赶紧用起来把。

 


免责声明!

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



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