Remote Validation in ASP.NET MVC

This article introduces how to implement remote validation in an ASP.NET MVC application.

Introduction

Most developers encounter a situation where it is necessary to check whether a user name already exists in the database before creating a new one, in other words we need to create a unique username in an application. All developers have a solution for this situation using a different approach but ASP.NET MVC has the feature of remote validation that solves such kinds of problems. 

Remote validation makes an ajax request that could be either GET or POST, calls a method that has at least one parameter and returns a result in JSON format. The parameter value is the model's property value on which the remote validation is implemented and returns a JSON value that can be either false or true. If it is true then it's not valid otherwise it's valid.

I would like to recommend more articles on ASP.NET MVC validation so that you could have a strong knowledge in this area. Other articles are:

  1. ASP.NET MVC Server-Side Validation
  2. ASP.NET MVC Client-Side Validation
  3. ASP.Net MVC Validation Using Fluent Validation
  4. Fluent Validation in ASP.Net MVC

Using the Code

To implement remote validation in an application we have two scenarios, one is without an additional parameter and the other is with an additional parameter. First we create an example without an additional parameter. In this example we check whether a username exists or not. If the username exists then that means the input user name is not valid. We create a view model class "UserViewModel" under the Models folder and that code is:

  1. using System.Web.Mvc;  
  2. namespace RemoteValidation.Models   
  3. {  
  4.     public class UserViewModel   
  5.     {  
  6.         public string UserName   
  7.         {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string Email   
  12.         {  
  13.             get;  
  14.             set;  
  15.         }  
  16.     }  
  17. }  

 

Now we create a static data source, in other words we create a static list of UserViewModel in which we could check whether a username exists or not. You can also use the database rather than a static list. The following code snippet is for StaticData.
  1. using RemoteValidation.Models;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace RemoteValidation.Code   
  5. {  
  6.     public static class StaticData   
  7.     {  
  8.         public static List < UserViewModel > UserList   
  9.         {  
  10.             get {  
  11.                 return new List < UserViewModel >   
  12.                 {  
  13.                     new UserViewModel   
  14.                     {  
  15.                         UserName = "Sandeep", Email = "sandeep.shekhawat88@hotmail.com"  
  16.                     },  
  17.                     new UserViewModel   
  18.                     {  
  19.                         UserName = "Raviendra", Email = "raviendra.shekhawat97@hotmail.com"  
  20.                     }  
  21.                 }  
  22.             }  
  23.         }  
  24.     }  
  25. }  
Now we create a controller "ValidationController" in which we create an action method to check whether a user name exists or not and return a result as a JSON format. If the username exists then it returns false so that the validation is implemented on the input field. The following code snippet shows ValidationController under the Controllers folder.
  1. using RemoteValidation.Code;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace RemoteValidation.Controllers   
  6. {  
  7.     public class ValidationController: Controller   
  8.     {  
  9.         [HttpGet]  
  10.         public JsonResult IsUserNameExist(string userName)   
  11.         {  
  12.             bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower())).FirstOrDefault() != null;  
  13.             return Json(!isExist, JsonRequestBehavior.AllowGet);  
  14.         }  
  15.     }  
  16. }  
Now we add remote validation on the UserName of the UserViewModel property as in the following code snippet.
  1. using System.Web.Mvc;  
  2.   
  3. namespace RemoteValidation.Models   
  4. {  
  5.     public class UserViewModel   
  6.     {  
  7.         [Remote("IsUserNameExist""Validation", ErrorMessage = "User name already exist")]  
  8.         public string UserName   
  9.         {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         public string Email   
  14.         {  
  15.             get;  
  16.             set;  
  17.         }  
  18.     }  
  19. }  
As in the preceding code snippet, the IsUserNameExist is a method of ValidationController that is called on the blur of an input field using a GET request. Now we create UserController under the Controllers folder to render a view on the UI.
  1. using RemoteValidation.Models;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace RemoteValidation.Controllers   
  5. {  
  6.     public class UserController: Controller   
  7.     {  
  8.         [HttpGet]  
  9.         public ActionResult AddUser()   
  10.         {  
  11.             UserViewModel model = new UserViewModel();  
  12.             return View(model);  
  13.         }  
  14.     }  
  15. }  
Now we add jquery.validate.js and jquery.validate.unobtrusive.js to the project and create a bundle as in the following code snippet.
  1. using System.Web.Optimization;  
  2.   
  3. namespace RemoteValidation.App_Start   
  4. {  
  5.     public class BundleConfig   
  6.     {  
  7.         public static void RegisterBundles(BundleCollection bundles)   
  8.         {  
  9.             bundles.Add(new StyleBundle("~/Content/css").Include(  
  10.                 "~/Content/css/bootstrap.css",  
  11.                 "~/Content/css/font-awesome.css",  
  12.                 "~/Content/css/site.css"));  
  13.   
  14.             bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  15.                 "~/Scripts/jquery-{version}.js"));  
  16.   
  17.             bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  18.                 "~/Scripts/jquery.validate*"));  
  19.         }  
  20.     }  
  21. }  
Thereafter we add the following keys in the web.config file.
  1. <add key="ClientValidationEnabled" value="true" />    
  2. <add key="UnobtrusiveJavaScriptEnabled" value="true" />    
Thereafter we create a view for the AddUser action method. The following code snippet is for the AddUser view.
  1. @model RemoteValidation.Models.UserViewModel  
  2.   
  3. < div class = "panel panel-primary" > < div class = "panel-heading panel-head" > Add User < /div>    
  4.     <div class="panel-body">    
  5.         @using (Html.BeginForm())    
  6.         {    
  7.             <div class="form-horizontal">    
  8.                 <div class="form-group">    
  9.                     @Html.LabelFor(model => model.UserName, new { @class = "col-lg-2 control-label" })    
  10.                     <div class="col-lg-9">    
  11.                         @Html.TextBoxFor(model => model.UserName, new { @class = "form-control" })    
  12.                         @Html.ValidationMessageFor(model => model.UserName)    
  13.                     </div > < /div>    
  14.                 <div class="form-group">    
  15.                     @Html.LabelFor(model => model.Email, new { @class = "col-lg-2 control-label" })    
  16.                     <div class="col-lg-9">    
  17.                         @Html.TextBoxFor(model => model.Email, new { @class = "form-control" })    
  18.                         @Html.ValidationMessageFor(model => model.Email)    
  19.                     </div > < /div>                    
  20.                 <div class="form-group">    
  21.                     <div class="col-lg-9"></div > < div class = "col-lg-3" > < button class = "btn btn-success"  
  22.                      id = "btnSubmit"  
  23.                      type = "submit" > Submit < /button>    
  24.                     </div > 
  25.                < /div>    
  26.             </div >  
  27. } < /div>    
  28. </div >   
  29. @section scripts   
  30. {  
  31.     @Scripts.Render("~/bundles/jqueryval")  
  32. }  
Let's run the application and put values into the user name field to execute the remote validation as in the following image.

Remote validation on user name
Figure 1: Remote validation on user name

Now we move to another option, we pass an additional parameter in the remote validation. We pass both the user name and email as a parameter and check whether the username and email combination exist or not on the email input. That's why we add one more method in ValidationController as in the following code snippet for it.
  1. [HttpGet]  
  2. public JsonResult IsUserExist(string email, string userName)   
  3. {  
  4.     bool isExist = StaticData.UserList.Where(u = > u.UserName.ToLowerInvariant().Equals(userName.ToLower()) && u.Email.ToLowerInvariant().Equals(email.ToLower())).FirstOrDefault() != null;  
  5.     return Json(!isExist, JsonRequestBehavior.AllowGet);  
  6. }  
Now we call this method on the Email property of UserViewModel as in the following code snippet.
  1. using System.Web.Mvc;  
  2.   
  3. namespace RemoteValidation.Models   
  4. {  
  5.     public class UserViewModel   
  6.     {  
  7.         [Remote("IsUserNameExist""Validation", ErrorMessage = "User name already exist")]  
  8.         public string UserName   
  9.         {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         [Remote("IsUserExist""Validation", ErrorMessage = "User already exist", AdditionalFields = "UserName")]  
  14.         public string Email   
  15.         {  
  16.             get;  
  17.             set;  
  18.         }  
  19.     }  
  20. }  
As in the preceding code snippet, we are passing an additional field using AdditionalFields in Remote. If we must pass more than one parameter then these will be comma-separated. Now run the application and the result will be as shown in the following image.

Remote validation with additional field
Figure 2: Remote validation with additional field