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:

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

  • 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.

  [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]

        public JsonResult IsClientNameAvailable(string ClientName)

        {

            List<string> lstClientName = new List<string>();

            lstClientName.Add("Mudita"); lstClientName.Add("Shalini"); lstClientName.Add("tanya sharma");

            if (lstClientName.Contains(ClientName))

                return Json(true, JsonRequestBehavior.AllowGet);

                return Json("User already exist", JsonRequestBehavior.AllowGet);

 

        }

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:

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Web;

using System.Web.Mvc;

 namespace validationWebAPI.Models

{

    public class User

    {
       [
DataType(DataType.Text)] 

        [Display(Name = "Client Name")]

        [Remote("IsClientNameAvailable", "User")]

        [Required(AllowEmptyStrings = false, ErrorMessage = "The client name can not be empty")]

        [StringLength(15, MinimumLength = 5, ErrorMessage = "Client Name field must have minimum 5 and maximum 15 character!")]

        public string ClientName { get; set; }

        [DataType(DataType.Password)]

        [Display(Name = "ClientPassword")]

        [Required(AllowEmptyStrings = false, ErrorMessage = "ClientPassword  cannot be empty!")]

        [StringLength(15, MinimumLength = 5, ErrorMessage = "ClientPassword must have minimum 5 and maximum 15 character!")]

        public string ClientPassword { get; set; }

        [DataType(DataType.Password)]

        [Display(Name = "Confirm ClientPassword")]

        [Required(AllowEmptyStrings = false, ErrorMessage = "Confirm ClientPassword cannot be empty!")]

        [System.Web.Mvc.Compare("ClientPassword", ErrorMessage = "ClientPassword and confirm Clientpassword must be same!")]

      public string ConfirmClientPassword { get; set; }

        [DataType(DataType.EmailAddress)]

        [Display(Name = "EmailID")]

        [Required(AllowEmptyStrings = false, ErrorMessage = "EmailID address  cannot be empty!")]

          public string EmailID { get; set; }

        [Display(Name = "Gender")]

        [Required(ErrorMessage = "Select your Gender")]

        public bool Gender { get; set; }

    }

    }

 

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:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.UI;

using validationWebAPI.Models;

namespace validationWebAPI.Controllers

{

    public class UserController : Controller

    {

       [HttpGet]

      public ActionResult UserRegistration()

        {

            return View();

        }

        [HttpPost]

        public ActionResult UserRegistration(User userModel)

        {

            if (ModelState.IsValid)

            {

               

            }

              else

               ModelState.AddModelError("ErrorMessage", "Check the errors");

            return View();

        }

        [OutputCache(Location = OutputCacheLocation.None, NoStore = true)]

        public JsonResult IsClientNameAvailable(string ClientName)

        {

            List<string> lstClientName = new List<string>();

            lstClientName.Add("Mudita"); lstClientName.Add("Shalini"); lstClientName.Add("tanya sharma");

            if (lstClientName.Contains(ClientName))

                return Json(true, JsonRequestBehavior.AllowGet);

                return Json("User already exist", JsonRequestBehavior.AllowGet);

 

        }

    }

}

 

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:

@model validationWebAPI.Models.User

@{

    ViewBag.Title = "UserRegistration";

    Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2>User Registration</h2>

<fieldset>

    <legend>New Employee Registration Page</legend>

    @using (@Html.BeginForm())

    {

        <div class="editor-label"> 

            @Html.LabelFor(p => p.ClientName)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(p => p.ClientName) @Html.ValidationMessageFor(p => p.ClientName)

        </div>

        <div class="editor-lable">

            @Html.LabelFor(p => p.ClientPassword)

        </div>

        <div class="editor-field">

            @Html.PasswordFor(p => p.ClientPassword) @Html.ValidationMessageFor(p => p.ClientPassword)

        </div>

        <div class="editor-label">

            @Html.LabelFor(p => p.ConfirmClientPassword)

        </div>

        <div class="editor=field">

            @Html.PasswordFor(p => p.ConfirmClientPassword) @Html.ValidationMessageFor(p => p.ConfirmClientPassword)

        </div>

        <div class="editor-lable">

            @Html.LabelFor(p => p.EmailID)

        </div>

        <div class="editor-field">

            @Html.TextBoxFor(p => p.EmailID, new { type = "emailid" }) @Html.ValidationMessageFor(p => p.EmailID)

        </div>

        <div class="editor-label">

            @Html.LabelFor(p => p.Gender)

        </div>

        <div class="editor-field">

            @Html.RadioButtonFor(p => p.Gender, false) Male @Html.RadioButtonFor(p => p.Gender, false)

            FeMale @Html.ValidationMessageFor(p => p.Gender)

        </div>

        <div style="margin-top: 20px; margin-bottom: 20px;">

            <input type="reset" value="Reset" />

            &nbsp;&nbsp;

            <input type="submit" value="Register"/>

        </div>

    }

</fieldset>

<script src="@Url.Content("~/Scripts/jquery-1.8.2.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>

    <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:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Routing;

 namespace validationWebAPI

{

   public class RouteConfig

    {

        public static void RegisterRoutes(RouteCollection routes)

        {

            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(

                name: "Default",

                url: "{controller}/{action}/{id}",

                defaults: new { controller = "User", action = "UserRegistration", id = UrlParameter.Optional }

            );

        }

    }

}


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

 

Up Next
    Ebook Download
    View all
    Learn
    View all