使用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