What is use of fluent Validation in C# and how to use in C#?

CsharpServer Side ProgrammingProgramming

FluentValidation is a .NET library for building strongly-typed validation rules. It Uses a fluent interface and lambda expressions for building validation rules. It helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic

To make use of fluent validation we have to install the below package

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

Example 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);
   }
}

Output

First Name is Empty
Length (1) of Last Name Invalid
raja
Published on 25-Nov-2020 11:41:41
Advertisements