Fluent Validation - How to use .NET library for building strongly-type validations rules in MVC Project (C#)
Fluent Validation is a validation library for .NET that uses a fluent interface to construct strongly-typed validation rules.
Steps.
1- Create a new project ASP .NET Web Application (.NET Framework) -> MVC project
2- Install the latest version through the Package Manager Console with the following command
Install-Package FluentValidation -Version 8.6.1
3-Create a new class Customer.
public class Customer
{
public string Surname { get; set; }
public string Forename { get; set; }
public bool HasDiscount { get; set; }
public decimal? Discount { get; set; }
public string Address { get; set; }
public string Postcode { get; set; }
}
4- Create a new validator for Customer.
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(x => x.Surname).NotEmpty();
RuleFor(x => x.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
RuleFor(x => x.Address).Length(20, 250);
RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode)
{
// custom postcode validating logic goes here
return !string.IsNullOrEmpty(postcode) && postcode.Length <= 4;
}
}
So, add "using FluentValidations" and "using Customer model".
5- Create a new controller for Customer class and a Create method (HTTP GET, HTTP POST)
Use ValidationResult to validate the model and add validation errors in ModelState.
public class CustomerController : Controller
{
// GET: Customer
public ActionResult Index()
{
return View();
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Models.Customer model)
{
CustomerValidator validator = new CustomerValidator();
ValidationResult validationResults = validator.Validate(model);
if (!validationResults.IsValid)
{
foreach (var error in validationResults.Errors)
{
ModelState.AddModelError(error.PropertyName, error.ErrorMessage);
}
}
if (ModelState.IsValid)
{
return RedirectToAction("MyAction", "MyController");
}
return View("Create", model);
}
}
6- Create a new strongly-typed view for Customer.
7- Then, click on the Create button of our view, we will get the following result.
So, that's it for this short post. I hope it helps you learn a little about how to use strongly typed validation rules.
Thank you for reading!
See you next time.