Validation Using Data Annotations Attribute

Introduction

This article describes 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 a 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.

    SelectMVC4Application.jpg

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

    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:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6. namespace DataAnnotationAPi.Models  
  7. {  
  8.     public class EmployeeModel  
  9.     {  
  10.         public int Id { getset; }  
  11.         [Required(ErrorMessage = "Enter Employee First Name")]  
  12.         public String EmpFirstName { getset; }  
  13.         [Required(ErrorMessage = "Enter Employee Last Name")]  
  14.         public String EmpLastName { getset; }  
  15.         [Required(ErrorMessage = "Enter Salary")]  
  16.         [Range(11000, 20000,ErrorMessage = "Salary should be more than 11000")]  
  17.         public int Salary { getset; }  
  18.     }  
  19. }  

Step 3

Create a Controller using the following procedure:

  • In the "Solution Explorer".
  • Right-click on the Controller folder.
  • Select "Add" -> "Controller" and change the name.

    Create Controller

  • Click on the "OK" button.

Add the following code: 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using DataAnnotationAPi.Models;  
  7. namespace DataAnnotationAPi.Controllers  
  8. {  
  9.     public class EmployeeController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Employee/  
  13.         public ActionResult GetEmployee()  
  14.         {  
  15.             return View();  
  16.         }  
  17.         [AcceptVerbs(HttpVerbs.Post)]  
  18.         public ActionResult GetEmployee([Bind(Exclude = "Id")]EmployeeModel P)  
  19.         {  
  20.             if (!ModelState.IsValid)  
  21.             {  
  22.                 return View();  
  23.             }  
  24.             return RedirectToAction("Index");  
  25.         }  
  26.     }  
  27. }  

Step 4

Create a View as in the following:

  • In the "EmployeeController".
  • Right-click on the "GetEmployee" action method.

    Create View

  • Click on the "Add" button.

Add the following code:

  1. @{  
  2.     ViewBag.Title = "GetEmployee";  
  3. }  
  4. <h2>GetEmployee</h2>  
  5. @model DataAnnotationAPi.Models.EmployeeModel  
  6. @{  
  7.     Layout = null;  
  8. }  
  9.     <div>  
  10.         @using (Html.BeginForm())  
  11.         {  
  12.             @Html.ValidationSummary(true)  
  13.             <p>    
  14.             @Html.LabelFor(m => m.EmpFirstName)  
  15.             @Html.TextBoxFor(m => m.EmpFirstName)  
  16.             @Html.ValidationMessageFor(m=>m.EmpFirstName)  
  17.             </p>  
  18.             <p>  
  19.             @Html.LabelFor(m=>m.EmpLastName)  
  20.             @Html.TextBoxFor(m => m.EmpLastName,"EmpLastName")  
  21.             @Html.ValidationMessageFor(m => m.EmpLastName)  
  22.             </p>  
  23.             <p>  
  24.                 @Html.LabelFor(m=> m.Salary)  
  25.                 @Html.TextBoxFor(m=>m.Salary,"Salary")  
  26.                 @Html.ValidationMessageFor(m=> m.Salary)  
  27.             </p>  
  28.             <input type="submit"value="Submit"/>  
  29.         }  
  30.     </div> 

Step 5

Change the code in the Route.config file:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7. namespace DataAnnotationAPi  
  8. {  
  9.     public class RouteConfig  
  10.     {  
  11.         public static void RegisterRoutes(RouteCollection routes)  
  12.         {  
  13.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  14.             routes.MapRoute(  
  15.                 name: "Default",  
  16.                 url: "{controller}/{action}/{id}",  
  17.                 defaults: new { controller = "Employee", action = "GetEmployee", id = UrlParameter.Optional }  
  18.             );  
  19.         }  
  20.     }  
  21. }  

Step 6

Execute the application.

GetEmployee View

Fill in a salary less than 11000 and leave one TextBox empty and click on the Submit button. The output will be:

Perform Validation


Similar Articles