FluentValidation是一个使用Linq表达式,非常流畅的小型业务对象验证组件。流畅也可以说优雅。类似链式操作。易于理解,功能完善。还可以配合MVC使用直接在页面进行验证,当你看到它的语法时,非常优雅,非常令人心动。看如下官网提供的一段验证代码:
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;
``
不仅可以使用Linq的操作,还能自带验证返回信息。更重要的是,组件内部已经封装好了10几种验证器。当然可以自定义一个复杂的哦。核心dll文件也不大,130多k。如果好用,可以自己移植到自己的系统哦。直接更好。
NuGet Packages:Install-Package FluentValidation
ASP.NET MVC集成包:Install-Package FluentValidation.MVC5
介绍 via cnblogs.com/asxinyu