首页 > 其他 > 详细

使用FluentValidation来进行数据有效性验证

时间:2014-06-09 20:19:59      阅读:281      评论:0      收藏:0      [点我收藏+]

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

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

bubuko.com,布布扣
    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;
bubuko.com,布布扣

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

 

使用FluentValidation来进行数据有效性验证,布布扣,bubuko.com

使用FluentValidation来进行数据有效性验证

原文:http://www.cnblogs.com/TianFang/p/3777060.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!