Introduction To Validation in ASP.Net Web API

Introduction

This article explains validation in the Web API. Here I show the step-by-step procedure to create the application using validation.

Validation

How validation works is like testing to determine that what the user entered in the field is valid. After validating the entered field, it checks that it is in the correct format, specified length, and you can compare the input value in various fields or against values. We can use the validation for various types of information. That will be explained by the sample application.

Types of Validation

Here we define the various types of validation that we can be use in our application. These are as follows:

  1. Required entry: It ensures the required field. The user cannot skip the entry.
  2. Compare Value: It is ensures that the comparison of the user's entry with the constant value or against the value of another constant or a specific data type. We use the comparison operator like equal, greater than, less than.
  3. Range checking: It checks the range of the input values with the minimum and maximum range that is required for the input value. We can use the range checker with the pairs of numbers, dates and alphabetic characters.
  4. Pattern matching: It is used for checking the pattern of an input value that specifies the sequence of characters.
  5. Remote: It is used for checking whether the value exists on the server side.

For implementing the validation we use the two namespaces "using System.ComponentModel.DataAnnotations" and
"using System.Web.Mvc".

Now we will see how validation works in the Web API application. Here is the sample of code that we use in our application:

  1. public class User  
  2. {  
  3.     [DataType(DataType.Text)]
  4.     [Display(Name = "Client Name")]  
  5.     [Remote("IsClientNameAvailable""User")]  
  6.     [Required(AllowEmptyStrings = false, ErrorMessage = "The client name can not be empty")]
  7.     [StringLength(15, MinimumLength = 5, ErrorMessage = "Client Name field must have minimum 5 and maximum 15 character!")]  
  8.     public string ClientName { getset; }  

  • In this code the "Remote" validation checks in the controller whether the "ClientName" is available or not.
  • The "Required" field validation specifies that the field is required. We cannot skip this field, if we do then it gives an error message.
  • "StringLength" defines the minimum and maximum length of the input value (in other words the minimum length is 5 and the maximum length is 15).[System.Web.Mvc.Compare("ClientPassword", ErrorMessage = "ClientPassword and confirm Clientpassword must be same!")]
  • "Compare" vallidation compares the two values "ClientPassword" and "Confirm ClientPassword". Both must be the same. If both are different then it displays an error message.

Now we provide the method for the Remote Validation.

  1. [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]  
  2. public JsonResult IsClientNameAvailable(string ClientName)  
  3. {  
  4.     List<string> lstClientName = new List<string>();  
  5.     lstClientName.Add("Mudita"); lstClientName.Add("Shalini"); lstClientName.Add("tanya sharma");  
  6.     if (lstClientName.Contains(ClientName))  
  7.         return Json(true, JsonRequestBehavior.AllowGet);  
  8.         return Json("User already exist", JsonRequestBehavior.AllowGet);  
  9. }

In the code above we use JSON binding for binding the remote validation with the method. In this code we add the three names "Mudita, Shalini, tanya sharma". If the "ClientName" is other than these three names then it displays the message "User already exists" otherwise it is allowed.

  • IsClientNameAvailable: Checks the availability of the ClientName.
  • lstClientName: Creates the list of the client names.
  • lstClientName.Add: Add a new client name to the list.
  • lstClientName.Contains: Determines whether a ClientName is contained in the list.

Let's see the procedure of creating this application.

Step 1

First create a Web API application as in the following:

  • Start Visual Studio 2012.
  • From the start Window select "New Project".
  • In the Template Window select "Installed" -> "Visual C#" -> "Web".
  • Select "ASP.NET MVC4 Web application" and click the "OK" button.

    val.jpg

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

    val1.jpg

  • Click the "Ok" button.

Step 2

Create a Model Class "User.cs" as in the following:

  • In the "Solution Explorer".
  • Right-click on the "Model" -> "Add" -> "Class".

    val2.jpg

  • Change the name and click the "OK" 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. using System.Web.Mvc;  
  7. namespace validationWebAPI.Models  
  8. {  
  9.     public class User  
  10.     {  
  11.         [DataType(DataType.Text)]   
  12.         [Display(Name = "Client Name")]  
  13.         [Remote("IsClientNameAvailable""User")]  
  14.         [Required(AllowEmptyStrings = false, ErrorMessage = "The client name can not be empty")]  
  15.         [StringLength(15, MinimumLength = 5, ErrorMessage = "Client Name field must have minimum 5 and maximum 15 character!")]  
  16.         public string ClientName { getset; }  
  17.         [DataType(DataType.Password)]  
  18.         [Display(Name = "ClientPassword")]  
  19.         [Required(AllowEmptyStrings = false, ErrorMessage = "ClientPassword  cannot be empty!")]  
  20.         [StringLength(15, MinimumLength = 5, ErrorMessage = "ClientPassword must have minimum 5 and maximum 15 character!")]  
  21.         public string ClientPassword { getset; }  
  22.         [DataType(DataType.Password)]  
  23.         [Display(Name = "Confirm ClientPassword")]  
  24.         [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm ClientPassword cannot be empty!")]  
  25.         [System.Web.Mvc.Compare("ClientPassword", ErrorMessage = "ClientPassword and confirm Clientpassword must be same!")]  
  26.         public string ConfirmClientPassword { getset; }  
  27.         [DataType(DataType.EmailAddress)]  
  28.         [Display(Name = "EmailID")]  
  29.         [Required(AllowEmptyStrings = false, ErrorMessage = "EmailID address  cannot be empty!")]  
  30.         public string EmailID { getset; }  
  31.         [Display(Name = "Gender")]  
  32.         [Required(ErrorMessage = "Select your Gender")]  
  33.         public bool Gender { getset; }  
  34.     }  
  35. } 

Step 3

Create a controller, "UserController" as in the following:

  • In the Solution Explorer.
  • Right-click on the "Controller" -> "Add" -> "Controller".

    val3.jpg

  • Change Name and click 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 System.Web.UI;  
  7. using validationWebAPI.Models;  
  8. namespace validationWebAPI.Controllers  
  9. {  
  10.     public class UserController : Controller  
  11.     {  
  12.         [HttpGet]  
  13.         public ActionResult UserRegistration()  
  14.         {  
  15.             return View();  
  16.         }  
  17.         [HttpPost]  
  18.         public ActionResult UserRegistration(User userModel)  
  19.         {  
  20.             if (ModelState.IsValid)  
  21.             {  
  22.             }  
  23.             else  
  24.                ModelState.AddModelError("ErrorMessage""Check the errors");  
  25.             return View();  
  26.         }  
  27.         [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]  
  28.         public JsonResult IsClientNameAvailable(string ClientName)  
  29.         {  
  30.             List<string> lstClientName = new List<string>();  
  31.             lstClientName.Add("Mudita"); lstClientName.Add("Shalini"); lstClientName.Add("tanya sharma");  
  32.             if (lstClientName.Contains(ClientName))  
  33.                 return Json(true, JsonRequestBehavior.AllowGet);  
  34.                 return Json("User already exist", JsonRequestBehavior.AllowGet);  
  35.         }  
  36.     }  
  37. }   

Step 4

Create a View as in the following:

  • In the "UserController".
  • Right-click on the action method "UserRegistration" -> "Add View".

    val4.jpg

    val5.jpg
  • Click the "OK" button.

Add the following code:

  1. @model validationWebAPI.Models.User  
  2. @{  
  3.     ViewBag.Title = "UserRegistration";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6. <h2>User Registration</h2>  
  7. <fieldset>  
  8.     <legend>New Employee Registration Page</legend>  
  9.     @using (@Html.BeginForm())  
  10.     {  
  11.         <div class="editor-label">   
  12.             @Html.LabelFor(p => p.ClientName)  
  13.         </div>  
  14.         <div class="editor-field">  
  15.             @Html.TextBoxFor(p => p.ClientName) @Html.ValidationMessageFor(p => p.ClientName)  
  16.         </div>  
  17.         <div class="editor-lable">  
  18.             @Html.LabelFor(p => p.ClientPassword)  
  19.         </div>  
  20.         <div class="editor-field">  
  21.             @Html.PasswordFor(p => p.ClientPassword) @Html.ValidationMessageFor(p => p.ClientPassword)  
  22.         </div>  
  23.         <div class="editor-label">  
  24.             @Html.LabelFor(p => p.ConfirmClientPassword)  
  25.         </div>  
  26.         <div class="editor=field">  
  27.             @Html.PasswordFor(p => p.ConfirmClientPassword) @Html.ValidationMessageFor(p => p.ConfirmClientPassword)  
  28.         </div>  
  29.         <div class="editor-lable">  
  30.             @Html.LabelFor(p => p.EmailID)  
  31.         </div>  
  32.         <div class="editor-field">  
  33.             @Html.TextBoxFor(p => p.EmailID, new { type = "emailid" }) @Html.ValidationMessageFor(p => p.EmailID)  
  34.         </div>  
  35.         <div class="editor-label">  
  36.             @Html.LabelFor(p => p.Gender)  
  37.         </div>  
  38.         <div class="editor-field">  
  39.             @Html.RadioButtonFor(p => p.Gender, false) Male @Html.RadioButtonFor(p => p.Gender, false)  
  40.             FeMale @Html.ValidationMessageFor(p => p.Gender)  
  41.         </div>  
  42.         <div style="margin-top: 20px; margin-bottom: 20px;">  
  43.             <input type="reset" value="Reset" />  
  44.                 
  45.             <input type="submit" value="Register"/>  
  46.         </div>  
  47.     }  
  48. </fieldset>  
  49. <script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>  
  50.     <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>  
  51.     <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>  
  52.     <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>   

Step 5

For execution of the application, we have made some changes in the "Route.Config.cs" file. This file exists:

  • In the "Solution Explorer".

  • Select "App_Start" -> "Route.Config.cs".

Change the Controller and Action Name. The code looks like this:

  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 validationWebAPI  
  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 = "User", action = "UserRegistration", id = UrlParameter.Optional }  
  18.             );  
  19.         }  
  20.     }  
  21. } 

If you do not want to change the file then you can execute the application and change the URL to "http://localhost:16739/User/UserRegistration". Then it executes properly.

Step 6

Execute the application by pressing "F5". It just look like this.

val6.jpg

When a value is inserted it displays a validation message.

val7.jpg

If the ClientName  "mudita" does not exist in the list then it displays a message. The image looks like this.

val9.jpg

If we leave a field empty then it also displays a message. See this image.

val8.jpg

 


Similar Articles