FluentValidation .NET 验证组件

FluentValidation是一个使用Linq表达式,非常流畅的小型业务对象验证组件。流畅也可以说优雅。类似链式操作。易于理解,功能完善。

还可以配合MVC使用直接在页面进行验证,当你看到它的语法时,非常优雅,非常令人心动。

而且它对ASP.NETCore支持十分友好,可以很方便的进行集成使用。

看如下官网提供的一段验证代码:

using FluentValidation;
public class CustomerValidator: AbstractValidator<Customer> {
  public CustomerValidator() {
    RuleFor(x => x.Surname).NotNull().NotEmpty().Length(1, 30);
    RuleFor(x => x.Forename).NotEmpty().WithMessage("Please specify a first name");
    RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
    RuleFor(x => x.Score).InclusiveBetween((byte)1, (byte)5);
    RuleFor(x => x.Score1).InclusiveBetween(0, 99999).When(x => x.Score1 != null);
    RuleFor(x => x.Score2).InclusiveBetween(0, 99999999.99m).When(x => x.Score2 != null);
    RuleFor(x => x.IsSeen).Must(x => { return x == 1 || x == 0; }).When(x => x.IsSeen != null);  
    RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
    RuleFor(x => x.Address).Length(20, 250);
  } 

  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;

要点:

  1. 必须继承于AbstractValidator
  2. AbstractValidator<需要验证的类>
  3. 在构造函数中添加验证
  4. RuleFor是对某一个属性添加验证规则

不仅可以使用Linq的操作,还能自带验证返回信息。更重要的是,组件内部已经封装好了10几种验证器。当然可以自定义一个复杂的。

NuGet Packages:Install-Package FluentValidation

ASP.NET MVC集成包:Install-Package FluentValidation.MVC5 

相关包:

核心:FluentValidation

.net:FluentValidation.Mvc5/FluentValidation.WebApi

.net core:FluentValidation.AspNetCore

 

posted @ 2021-07-08 17:56  以德为先  阅读(80)  评论(0编辑  收藏  举报