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,
Choose a template
Install the required Fluent Validation libraries.
For this, go to menu bar select Tools => NuGet Package Manager => Manage NuGet Packages for Solution
Browse for ‘fluentvalidation.aspnetcore’ and install the latest stable package.
Modify 'startup.cs' file
Go to ‘startup.cs’ and add the below lines of code in the ConfigureServices method.
- services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1).AddFluentValidation(c => c.RegisterValidatorsFromAssemblyContaining<Startup>());
- services.AddTransient<IValidatorFactory, ServiceProviderValidatorFactory>();
Include references for FluentValidation and FluentValidation.AspNetCore in startup.cs
- using FluentValidation;
- using FluentValidation.AspNetCore;
Create Model Classes
Create a class called ‘Employee.cs’ ( this class object will be validated ) in the ‘Models’ folder.
Code for Employee.cs class
- namespace ValidateJsonList.Models
- {
- public class Employee
- {
- public string Name;
- public string EmailId;
- }
- }
Create another class called ‘Employees.cs’ in ‘Models’ folder.
Code for Employees.cs class
- namespace ValidateJsonList.Models
- {
- using System.Collections.Generic;
-
- public class Employees
- {
- public List<Employee> Employee;
- }
- }
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
- namespace ValidateJsonList.Validators
- {
- using FluentValidation;
- using ValidateJsonList.Models;
-
- public class EmployeeValidator : AbstractValidator<Employee>
- {
- public EmployeeValidator()
- {
- RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required!");
- RuleFor(x => x.EmailId).NotEmpty().WithMessage("Email is required!");
- RuleFor(x => x.EmailId).EmailAddress().WithMessage("Enter a valid Email Address");
- }
- }
- }
Code for EmployeesValidator.cs
- namespace ValidateJsonList.Validators
- {
- using FluentValidation;
- using ValidateJsonList.Models;
-
- public class EmployeesValidator : AbstractValidator<Employees>
- {
- public EmployeesValidator()
- {
- RuleForEach(x => x.Employee).SetValidator(new EmployeeValidator());
- }
- }
- }
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
- namespace ValidateJsonList.Controllers
- {
- using Microsoft.AspNetCore.Mvc;
- using ValidateJsonList.Models;
-
- [Route("api/[controller]")]
- [ApiController]
- public class EmployeeController : ControllerBase
- {
- [HttpPost]
- [Route("PostData")]
- public ActionResult PostData(Employees employee)
- {
- if (ModelState.IsValid)
- {
- return Ok();
- }
- else
- {
- return BadRequest();
- }
- }
- }
- }
But, since we are inheriting the controller from ControllerBase, code of the Postdata action method can be like this
- [HttpPost]
- [Route("PostData")]
- public ActionResult PostData(Employees employee)
- {
- return Ok();
- }
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
- In Postman, set the HTTP method to POST.
- Select the Body tab.
- Select the raw radio button.
- Set the type to JSON (application/json).
- In the request body enter JSON for Employees item and click on send button
Employees item JSON Schema.
JSON list of employee object is like this,
- First object is having value for Name but not for EmailId
- Second object is having value for EmailId but not for Name
- Third object is having value for Name and value for EmailId, but EmailId format is incorrect.
Response after sending the data.
Response JSON will have validation messages for all invalid properties of employee object ( invalidated ) in the JSON list.