C# 中 Fluent Validation 的用途是什么?如何在 C# 中使用?

csharpserver side programmingprogramming更新于 2025/10/17 13:22:17

FluentValidation 是一个用于构建强类型验证规则的 .NET 库。它使用 Fluent 接口和 Lambda 表达式来构建验证规则。它有助于清理您的域代码并使其更具凝聚力,同时为您提供一个单一的验证逻辑查找位置。

要使用 Fluent Validation,我们必须安装以下软件包

<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

相关文章