In this article we will discuss Model Validation using fluent Validation in Asp.net Core. When working with application in ASP.Net Core, we will often want to validate your model class to ensure that the data they contain conform to the pre-defined validation rules.
One of the requirements for a good API is the ability to validate input relying on different business rules. As developers, we have to always care about validation when getting any data from client.
Previous Article Also check Create CRUD Web API in Asp.Net Core With Dapper ORM and Sqlite
Prerequisites
- Download and install .Net Core 6.0 SDK from here
- Download and Install Microsoft Visual Studio 2022 from here
Create ASP.Net Core Web API
- Open visual studio and click the Create New Project Option
- Select the Template
- Enter the name of the Project
Select the Framework and Click on Create
Install NuGet Packages
- FluentValidation.AspNetCore
Create Model
For example we have an customer class with fields FirstName, Email, Age and phonenumber as shown below
using FluentValidation; using System.ComponentModel.DataAnnotations; namespace Fluent_Model_Validation.Models { public class Customer { public string FirstName { get; set; } public string Email { get; set; } public string PhoneNumber { get; set; } public int Age { get; set; } } public class Customervalidator : AbstractValidator<Customer> { public Customervalidator() { RuleFor(p => p.FirstName).Length(0,25); RuleFor(p => p.Email).NotEmpty().EmailAddress(); RuleFor(p => p.PhoneNumber).Length(0,12); RuleFor(p => p.Age).InclusiveBetween(18,80); } } }
Now add a new validator with our rule directly in the customer class
We create a class customervalidator that inherits from the abstractValidator<T> from FluentValidation .
Create Controller
using Fluent_Model_Validation.Models; using Microsoft.AspNetCore.Mvc; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Fluent_Model_Validation.Controllers { [Route("api/[controller]")] [ApiController] public class FluentController : ControllerBase { // GET: api/<FluentController> // POST api/<FluentController> [HttpPost] public Customer Post([FromBody] Customer model) { return model; } } }