Validation Using Data Annotations Attribute

This article describess Validation using Data Annotation. We use the "System.ComponentModel.DataAnnotations" namespace that specifies the validation for every individual field in the data model. These attributes define the validation of range checking and required fields.

The following is the procedure for creating the application.

Step 1

Create an Web API application using the following procedure:

Start Visual Studio 2012.

From the Start window select "Installed" -> "Visual C#" -> "Web".

Select "ASP.NET MVC4 Web Application" and click on the "OK" button.

From the "MVC4 Project" window select "Web API".

Click on the "OK" button.

Step 2

Create a Model Class using the following procedure:

In the "Solution Explorer".

Right-click on the Model Folder.

Select "Add" -> "Class".

Select "Installed" -> "Visual C#" and select class.

Click on the "Add" button.

Add the following code:

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

namespace DataAnnotationAPi.Models

{

publicclassEmployeeModel

{

publicint Id { get; set; }

[Required(ErrorMessage = "Enter Employee First Name")]

publicString EmpFirstName { get; set; }

[Required(ErrorMessage = "Enter Employee Last Name")]

publicString EmpLastName { get; set; }

[Required(ErrorMessage = "Enter Salary")]

[Range(11000, 20000,ErrorMessage = "Salary should be more than 11000")]