FluentValidation เป็นไลบรารี .NET สำหรับสร้างกฎการตรวจสอบที่พิมพ์อย่างเข้มงวด ใช้อินเทอร์เฟซที่คล่องแคล่วและนิพจน์แลมบ์ดาสำหรับการสร้างกฎการตรวจสอบ ช่วยล้างรหัสโดเมนของคุณและทำให้มีความสอดคล้องกันมากขึ้น รวมทั้งให้ที่เดียวในการค้นหาตรรกะการตรวจสอบความถูกต้อง
เพื่อที่จะใช้การตรวจสอบอย่างคล่องแคล่ว เราต้องติดตั้งแพ็คเกจด้านล่าง
<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