Skip to content

How to Validate Model Data in ASP.NET Core MVC and Web API

Model Validation: In simple words, validation means checking something (items, tasks or data) against predefined conditions or rules. When we develop large-scale applications where data security is a big concern, we should not rely on the data users enter. The mechanism that checks whether user input meets the defined standards and business rules is called input validation or model validation.

What should we check in model validation?

There are many things to check during validation, such as null values for IDs used to fetch data from the database, string length, email addresses, currency values, dates of birth, phone numbers, characters entered in integer fields, mandatory fields, comparing two strings, and so on.

We can implement validation at three levels:

  • Client-Side Validation
  • Server-Side Validation
  • Database Validation

Client-Side Validation: Client-side validation is done in the user's browser using JavaScript or jQuery libraries. When a user fills in a form, client-side validation immediately shows a message if anything does not meet the defined rules. This type of validation is not reliable on its own, because users can disable JavaScript in their browser settings, and then it does not work, so we cannot ensure data security. Client-side validation has a few key features:
1. It works with JavaScript or jQuery Unobtrusive Validation in the browser.
2. Users can disable or manipulate the scripts.
3. Client-side validation is fast because it gives an immediate result.
4. It saves a round trip to the server.

Server-Side Validation: Server-side validation is always performed on the server, so it is secure: it works even when JavaScript is disabled in the browser. It is a little slower than client-side validation, because the form data is posted to the server and validated there against the business rules. If there is an error, the server sends back a response with error messages, which are shown to the user. We can use validation attributes from Data Annotations to perform server-side validation.

Database Validation: Database validation is performed in the database. It is the last line of defence, making sure only correct data is stored and protecting database integrity. We can apply check constraints to the tables so that only valid data can be inserted, and we can prevent duplicate entries with unique key constraints.

Different ways to implement validation in ASP.NET Core

There are three main ways to implement model validation in ASP.NET Core:

  • Data Annotations: Data Annotations are built-in validation attributes in ASP.NET Core, provided by the System.ComponentModel.DataAnnotations namespace. They are simple to implement with attributes on model class properties.
  • FluentValidation: FluentValidation is another way to implement model validation. We install the FluentValidation.DependencyInjectionExtensions library from the NuGet Package Manager, then create a validator class and define the rules in it using a fluent syntax.
  • Custom Validation: Based on our requirements, we can create custom validation logic using the IValidatableObject interface or custom validation attributes.

Implementation of Data Annotations in a Model Class

Create an Employee model class and add the System.ComponentModel.DataAnnotations namespace, which provides Data Annotations in ASP.NET Core. Add the properties below and use attributes such as Required, EmailAddress, DisplayName and StringLength, which validate the data on the server when you post it and send the response back to the client. Below is a screenshot of the Employee model class.

Employee model class with data annotation validation attributes

In the image above, the Name property is decorated with the Required and DisplayName attributes. Required shows an error message if no value is entered for Name, and DisplayName sets the label text in the view.
Apart from Required and DisplayName, you can use StringLength, EmailAddress, Phone and other attributes for different purposes.

Implementation of FluentValidation in ASP.NET Core for Model Validation

In ASP.NET Core, FluentValidation is a .NET library for validating model classes. Install it in your application using the NuGet Package Manager. After installing it, add validator classes and define the validation rules for the properties of your model classes, as you can see in the image below.

First, install the FluentValidation package from the Package Manager Console, as shown in the image below.

Installing the FluentValidation package from Package Manager Console

After installing the package, you can see it in the Packages folder under the project's Dependencies, as shown below.

FluentValidation package under Dependencies in Solution Explorer

Create a validator class, EmployeeValidator, that inherits from the base AbstractValidator class, and define the rules for Name, Password and Email in its constructor, as shown in the image below.

EmployeeValidator class defining FluentValidation rules for name, password and email

To use FluentValidation, register this validator class in Program.cs, as shown in the code below.

builder.Services.AddControllers().AddFluentValidation
  (flentVal => flentVal.RegisterValidatorsFromAssemblyContaining<EmployeeValidator>());