How to validate model data in ASP.NET Core MVC and Web API

Model Validation :- In simple words validation means checking on something(Items/task/data) based on predefined conditions or based on some rules. When we develop large scale applications where data security is a big concern , In that case we should not rely on the Users inserted data, we need to develop a mechanism by which we can check the inputs provided by the users are upto defined standard or satisfies the business rules is called the input validation or model validation.

What things we should check in Model Validations ?

There are many things we need to check during validation like null values for Id's used in fetching the data from database,Length of strings,Email address validation,Currency validation,validation on date of birth,validation of phone numbers,validation on characters inserted for integer values,validation for mandatory field values, validation on comparing two strings and so on.

We can implement validation on below three types.

  • Client Side Validation
  • Server Side Validation
  • Database Validation

Client Side Validation :- As we know that Client Side Validatin is done on Clients browser using the Javascript or Jquery libraries. Whenever any user fills the UI form then client side validation immidiately provides the validation message if anything is not upto defined rules. This type of validation is not reliable in terms of browsers operatability because user can disable the browsers javascript using browsers settings, then it will not work so in that case we can not ensure the data security. So Client side validation has few key features like
1. It is works on browsers javascript or Jquery Unobtrusive validation.
2. User can disable or manipulate the scripts.
3. Client side validation is fast in terms of performance because it provides immidiate result.
4.It saves the server round trip.

Server Side Validation :- Server Side Validation always performed on Server only so that it is always secure because it will also works when browser's javascript is disabaled. Server Side Validation is little bit slow as comapre to Client Validation because all the forms data is posted on the server and then validation is performed their based on defined business rules so if any error is there then it will send a response back with error messages and displays to end users. We can use the Validation Attributes using Data Annotations to perform Server Side Validations.

Database Validation :- Database Validation always performed on Database only so that it is the bottom line of validation of data so that correct and desired data will be stored on database and ensures the database integrity. We can apply some Check Constraints on the database tables so that only valid data can only insert into the database tables. We can restricts duplicate entries in database tables using the Unique key constraints on database.

Different ways to implement validations in ASP.Net Core

There are mainly four ways to implement model validation in ASP.Net core which is listed below :-

  • Data Annotaions :- Data Annotations is an built in validations in ASP.Net core and we can perform it using the System.ComponentModel.DataAnnotations library . DataAnnotation is simple to implement using the attributes applied on model class properties.
  • Fluent API :- Fluent API is a another way of implementing the Model Validation using the API's that we need to install the FluentValidations.DependencyInjectionExtensions library from Nuget Package Manager and then we need to create Validator Class and defined the rules in that using the Fluent API.
  • Custom Validation :- Based on our requirements we can create Custom Validation logic using IValidatable Interface and using the Custom Validation attributes.

Implementation of Data Annotation in Model Class

Create a Employee Model class and add the namespace using System.ComponentModel.DataAnnotations into the Employee Model class that is used for Data Annotations in ASP.Net Core and create below properties into Employee Model class and use the Required,EmailAddress,DisplayName,StringLength like few attributes that will check the validation on server when you post data on serevr and validate it and send the response back to client. Below is the screen share of Employee Model class.

Image is not available

In the above image you can see I have decorated Name property with Required and DisplayName attributes which will check if you have not entered any values or data into Name then it will through an error message and DisplayName property is used for displaying the label text into the view.
Apart from Required,DisplayName you can use StringLength,EmailAddress Phone and other properties for different purposes.

Implementation of Fluent API in ASP.Net Core for Model Validation

In ASP.Net core fluent validation is a .Net Library used for validation of model class. You need to install Fluent API in your application using the Nuget Package Manager. After installation of Fluent API you need to add validator classes and need to define the rules for validation on properties of Model Classes as you can see in below image.

Image is not available
Image is not available

Created one Validator Class that is Employee Validator and it inherits from the base AbstractValidator class and we define the Rules in constructor of class for Name,Password and Email as shown in below image.

Image is not available

For using the Fluent Validations we need to register this Validator Class in program.cs as shown by below code.


  builder.Services.AddControllers().AddFluentValidation
    (flentVal => flentVal.RegisterValidatorsFromAssemblyContaining());
                 
                
Image is not available

About the Author
Sudheer Singh Chouhan is a Software Engineer having Expertise in Development Design and Architecting the applications , Project Management , Designing Large Scale Databases in SQL Server since last 17 Years.
Skill Sets :- Microsoft .NET technologies like ASP.Net Core, Web API, LINQ, Web Forms, WinForms, SQL Server, EntityFramework, Design Patterns, Solid Principles, Microservices, AWS Cloud.