Model Validation in ASP.NET Web API

Model in MVC is a representation of our data structure so we need to validate the input data by applying validation on model. Here for that purpose we will implement the data annotation technique for applying model validation in Asp.NET Web API application.

In order to use the Data Annotations Model in an ASP.NET MVC application, we first need to add 2 references in the application:
1. Microsoft.Web.Mvc.DataAnnotations.dll assembly
2. System.ComponentModel.DataAnnotations.dll assembly

For example, We will use a model class like Student and apply validation on it using annotation. For that we need to use or import System.ComponentModel.DataAnnotations namespace. We will apply the different validate attributes to model class properties eg.

We can check the validity of Model against the defined validation rules in controller class by using ModelState.IsValid i.e.

Now, when the client will send a POST request in JSON format, it will be converted to Student object instance and will be validated against the model rules.
If we send the data like :

This request will give us the validation error for ClassName and return the response with the message “Bad Request….Request is Invalid….” because it is required field which is not supplied.

In this way, there are many other annotation attributes for validating the model properties by using ComponentModel.DataAnnotations namespace:

Range – Enables you to validate whether the value of a property falls between a specified range of values.
ReqularExpression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
Required – Enables you to mark a property as required.
StringLength – Enables you to specify a maximum length for a string property.
Validation – The base class for all validator attributes.

Like this Post? Share