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


FluentValidation 是一個用於構建強型別驗證規則的 .NET 庫。它使用流暢介面和 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

更新日期: 25-11-2020

2K+ 瀏覽

開啟你的職業生涯

完成該課程並獲得認證

開始
廣告
© . All rights reserved.