在C#中流利验证的用途是什么?在C#中如何使用?

FluentValidation是用于构建强类型验证规则的.NET库。它使用流畅的界面和lambda表达式来构建验证规则。它有助于清理域代码并使之更具凝聚力,并为您提供寻找验证逻辑的单一位置

要使用流利的验证,我们必须安装以下软件包

<PackageReference Include="FluentValidation" Version="9.2.2" />

例子1

static class Program {
   static void Main (string[] args) {
      List errors = new List();

      PersonModel person = new PersonModel();
      person.FirstName = "";
      person.LastName = "S";
      person.AccountBalance = 100;
      person.DateOfBirth = DateTime.Now.Date;

      PersonValidator validator = new PersonValidator();
      ValidationResult results = validator.Validate(person);

      if (results.IsValid == false) {
         foreach (ValidationFailure failure in results.Errors) {
            errors.Add(failure.ErrorMessage);
         }
      }
      foreach (var item in errors) {
         Console.WriteLine(item);
      }
      Console.ReadLine ();
   }
}

public class PersonModel {
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public decimal AccountBalance { get; set; }
   public DateTime DateOfBirth { get; set; }
}

public class PersonValidator : AbstractValidator {
   public PersonValidator(){
      RuleFor(p => p.FirstName)
      .Cascade(CascadeMode.StopOnFirstFailure)
      .NotEmpty().WithMessage("{PropertyName} is Empty")
      .Length(2, 50).WithMessage("Length ({TotalLength}) of {PropertyName} Invalid")
      .Must(BeAValidName).WithMessage("{PropertyName} Contains Invalid Characters");

      RuleFor(p => p.LastName)
      .Cascade(CascadeMode.StopOnFirstFailure)
      .NotEmpty().WithMessage("{PropertyName} is Empty")
      .Length(2, 50).WithMessage("Length ({TotalLength}) of {PropertyName} Invalid")
      .Must(BeAValidName).WithMessage("{PropertyName} Contains Invalid Characters");

   }

   protected bool BeAValidName(string name) {
      name = name.Replace(" ", "");
      name = name.Replace("-", "");
      return name.All(Char.IsLetter);
   }
}

输出结果

First Name is Empty
Length (1) of Last Name Invalid