Validate A JSON List Of Objects In ASP.NET Core Using Fluent Validation

In this article we will read about how to validate and check data of a JSON list of objects in ASP.Net Core using Fluent Validation. Let’s start.
 
First, create a new ASP.Net Core project,
 
Validate a JSON list of Objects in ASP.NET Core using Fluent Validation
 

Choose a template

 
Validate a JSON list of Objects in ASP.NET Core using Fluent Validation
 
Install the required Fluent Validation libraries.
 
For this, go to menu bar select Tools => NuGet Package Manager => Manage NuGet Packages for Solution
 
Validate a JSON list of Objects in ASP.NET Core using Fluent Validation
 
Browse for ‘fluentvalidation.aspnetcore’ and install the latest stable package.
 
Validate a JSON list of Objects in ASP.NET Core using Fluent Validation
 

Modify 'startup.cs'  file

 
Go to ‘startup.cs’ and add the below lines of code in the ConfigureServices method.
  1. services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddFluentValidation(c => c.RegisterValidatorsFromAssemblyContaining<Startup>());  
  2. services.AddTransient<IValidatorFactory, ServiceProviderValidatorFactory>();  
Include references for FluentValidation and FluentValidation.AspNetCore in startup.cs 
  1. using FluentValidation;  
  2. using FluentValidation.AspNetCore;  
Validate a JSON list of Objects in ASP.NET Core using Fluent Validation
 
Validate a JSON list of Objects in ASP.NET Core using Fluent Validation
 

Create Model Classes

 
Create a class called ‘Employee.cs’ ( this class object will be validated ) in the ‘Models’ folder.
 
Code for Employee.cs class
  1. namespace ValidateJsonList.Models  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         public string Name;  
  6.         public string EmailId;  
  7.     }  
  8. }  
Create another class called ‘Employees.cs’ in ‘Models’ folder.
 
Code for Employees.cs class
  1. namespace ValidateJsonList.Models  
  2. {  
  3.     using System.Collections.Generic;  
  4.   
  5.     public class Employees  
  6.     {  
  7.         public List<Employee> Employee;  
  8.     }  
  9. }
This class contains Employee property of type List<Employee> to hold collection of Employee objects.
 

Create AbstractValidator classes for validation rules

 
Now, create AbstractValidator classes for both Employee.cs and Employees.cs. I have created a ‘Validators’ folder for having all the AbstractValidator classes at one place.
 
Code for EmployeeValidator.cs
  1. namespace ValidateJsonList.Validators  
  2. {  
  3.     using FluentValidation;  
  4.     using ValidateJsonList.Models;  
  5.   
  6.     public class EmployeeValidator : AbstractValidator<Employee>  
  7.     {  
  8.         public EmployeeValidator()  
  9.         {  
  10.             RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required!");  
  11.             RuleFor(x => x.EmailId).NotEmpty().WithMessage("Email is required!");  
  12.             RuleFor(x => x.EmailId).EmailAddress().WithMessage("Enter a valid Email Address");  
  13.         }  
  14.     }  
  15. }  
Code for EmployeesValidator.cs
  1. namespace ValidateJsonList.Validators  
  2. {  
  3.     using FluentValidation;  
  4.     using ValidateJsonList.Models;  
  5.   
  6.     public class EmployeesValidator : AbstractValidator<Employees>  
  7.     {  
  8.         public EmployeesValidator()  
  9.         {  
  10.             RuleForEach(x => x.Employee).SetValidator(new EmployeeValidator());  
  11.         }  
  12.     }  
  13. }  
Both EmployeeValidator.cs and EmployeesValidator.cs are inherited from AbstractValidator<T>, which is a part of FluentValidation namespace.
 

Create Controller

 
Now, create an Empty API controller called ‘EmployeeController’. Inherit it from ControllerBase. More about Controllerbase can be found at here.
 
Code for EmployeeController.cs 
  1. namespace ValidateJsonList.Controllers  
  2. {  
  3.     using Microsoft.AspNetCore.Mvc;  
  4.     using ValidateJsonList.Models;  
  5.   
  6.     [Route("api/[controller]")]  
  7.     [ApiController]  
  8.     public class EmployeeController : ControllerBase  
  9.     {  
  10.         [HttpPost]  
  11.         [Route("PostData")]  
  12.         public ActionResult PostData(Employees employee)  
  13.         {  
  14.             if (ModelState.IsValid)  
  15.             {  
  16.                 return Ok();  
  17.             }  
  18.             else  
  19.             {  
  20.                 return BadRequest();  
  21.             }  
  22.         }  
  23.     }  
  24. }  
But, since we are inheriting the controller from ControllerBase, code of the Postdata action method can be like this
  1. [HttpPost]  
  2.        [Route("PostData")]  
  3.        public ActionResult PostData(Employees employee)  
  4.        {  
  5.            return Ok();  
  6.        }  
No need to write return BadRequest(); explicitly. The [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response
 

Test API end point

 
To test Postdata end point, we will use Postman.
 
Build the project
  1. In Postman, set the HTTP method to POST.
  2. Select the Body tab.
  3. Select the raw radio button.
  4. Set the type to JSON (application/json).
  5. In the request body enter JSON for Employees item and click on send button
Employees item JSON Schema. 
  1. {"employee": [
  2.    { 
  3.       "Name""John Doe",  
  4.       "Email":""
  5.    },  
  6.    {  
  7.       "Name""",  
  8.       "EmailId":"[email protected]"  
  9.    },  
  10.    {  
  11.       "Name""John Doe",  
  12.       "EmailId":"email@[email protected]"  
  13.    }
  14. ]}  
Validate a JSON list of Objects in ASP.NET Core using Fluent Validation
 
JSON list of employee object is like this,
  1. First object is having value for Name but not for EmailId
  2. Second object is having value for EmailId but not for Name
  3. Third object is having value for Name and value for EmailId, but EmailId format is incorrect.
Response after sending the data.
 
Validate a JSON list of Objects in ASP.NET Core using Fluent Validation
 
Response JSON will have validation messages for all invalid properties of employee object ( invalidated ) in the JSON list.