Remote Validation In MVC 5 To Check If UserName and Email Id Exists

Introduction

In this article, I am going to explain about "Remote Validation", using MVC 5. Remote Validation is mainly used to check if the user or Mail ID exists or not in a database. Also, you can use it for any type of validation using Remote Attribute.

Most of the Web Applications need to validate the user or mail ID in the database. For this, the developers need to write huge amount of code. Due to this, I am going to achieve this task in very simple steps. Remote Validation normally works as jQuery validation.

Introduction

Before learning about "Remote Validation", if you are beginner in MVC, you should read these - 

What is Remote Validation? 

Remote Validation permits the developer to call the controller action, using client side script. This is valuable when you need to perform out a back end query without performing a full Server side Postback.

Implement of "Remote Validation" in MVC Application.

Remote Validation is only an AJAX call, which approves the client's information. This can undoubtedly be proficient without using ASP.NET MVC 5. The situation for our demo is very basic. We have to ensure that the EmpName of the new user is one of a kind. The execution beneath makes a basic structure, which contains the TextBox control with the Id EmpName and other TextBox control with Id EmpMail.

Follow some simple steps to use remote validation in MVC 5

Step 1 - Create a MVC Application. See the image, given below-

remote validation

Step 2 - Create a model "Employee.cs" inside "Model" folder. Use the code, given below-

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace RemoteValidation.Models {  
  8.     public class Employee {  
  9.         //To Check userName   
  10.         [Remote("IsEmpNameExist", "Validation", ErrorMessage = "Employee name already exist")]  
  11.         public string EmpName {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         //check User name and mailId.   
  16.         [Remote("IsEmpNameandMailExist", "Validation", ErrorMessage = "EmialId is already exist"AdditionalFields = "EmpName")]  
  17.         public string EmpMail {  
  18.             get;  
  19.             set;  
  20.         }  
  21.     }  
  22.     //Set static value in model.   
  23.     public static class EmployeeStaticData {  
  24.         public static List < Employee > UserList {  
  25.             get {  
  26.                 return new List < Employee > {  
  27.                     new Employee {  
  28.                         EmpName = "Bikesh"EmpMail = "Bikesh.srivastava@hytechpro.com"  
  29.                     },  
  30.                     new Employee {  
  31.                         EmpName = "Navdeep"EmpMail = "Navdeep.kumar@hytechpro.com"  
  32.                     }  
  33.   
  34.                 };  
  35.             }  
  36.         }  
  37.   
  38.     }  
  39. }  
Step 3 - Create a Controller "ValidationController.cs" to Implement the Validation. In this Controller, I am creating an action, which is used to check, if the user exists or not. Also, you can check any type of the Validation. 
  1. using RemoteValidation.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace RemoteValidation.Controllers {  
  9.     public class ValidationController: Controller {  
  10.         //For check both at a time .mailid and empName.   
  11.         [HttpGet]  
  12.         public JsonResult IsEmpNameandMailExist(string Empname, string EmpMail) {  
  13.   
  14.                 bool isExist = EmployeeStaticData.UserList.Where(u => u.EmpName.ToLowerInvariant().Equals(Empname.ToLower()) && u.EmpMail.ToLowerInvariant().Equals(EmpMail.ToLower())).FirstOrDefault() != null;  
  15.                 return Json(!isExist, JsonRequestBehavior.AllowGet);  
  16.             }  
  17.             //To check only EmpName   
  18.             [HttpGet]  
  19.         public JsonResult IsEmpNameExist(string Empname) {  
  20.   
  21.             bool isExist = EmployeeStaticData.UserList.Where(u => u.EmpName.ToLowerInvariant().Equals(Empname.ToLower())) != null;  
  22.             return Json(!isExist, JsonRequestBehavior.AllowGet);  
  23.         }  
  24.     }  
  25. }  
Step 4 - Create Controller to execute your action. Here, you can create any type of action to perform your task. Use the code, given below-
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using RemoteValidation.Models;  
  7.   
  8. namespace RemoteValidation.Controllers {  
  9.     public class EmployeeController: Controller {  
  10.         //my action   
  11.         [HttpGet]  
  12.         public ActionResult AddUser() {  
  13.             Employee model = new Employee();  
  14.             return View(model);  
  15.         }  
  16.   
  17.     }  
  18. }  
Step 5 - Right click on Action name "AddUser" add view. In this View, I am binding model "Employee". Using Razor control, I am creating a login page, which is designed, using bootstrap, CSS, and jQuery. Use the code, given below-
  1. @model RemoteValidation.Models.Employee  
  2.   
  3.     <  
  4.     div class = "panel panel-primary" >  
  5.     <  
  6.     div class = "panel-heading panel-head" > Add User < /div>  <  
  7.     div class = "panel-body" >  
  8.     @using(Html.BeginForm()) { <  
  9.         div class = "form-horizontal" >  
  10.             <  
  11.             div class = "form-group" >  
  12.             @Html.LabelFor(model => model.EmpName, new {  
  13.                 @class = "col-lg-2 control-label"  
  14.             }) <  
  15.             div class = "col-lg-9" >  
  16.             @Html.TextBoxFor(model => model.EmpName, new {  
  17.                 @class = "form-control"  
  18.             })  
  19.         @Html.ValidationMessageFor(model => model.EmpName) <  
  20.             /div> </div >  
  21.             <  
  22.             div class = "form-group" >  
  23.             @Html.LabelFor(model => model.EmpMail, new {  
  24.                 @class = "col-lg-2 control-label"  
  25.             }) <  
  26.             div class = "col-lg-9" >  
  27.             @Html.TextBoxFor(model => model.EmpMail, new {  
  28.                 @class = "form-control"  
  29.             })  
  30.         @Html.ValidationMessageFor(model => model.EmpMail) <  
  31.             /div>  <  
  32.             /div>  <  
  33.             div class = "form-group" >  
  34.             <  
  35.             div class = "col-lg-9" > < /div> <div class="col-lg-3">  <  
  36.             button class = "btn btn-success"  
  37.         id = "btnSubmit"  
  38.         type = "submit" >  
  39.             Submit <  
  40.             /button>  <  
  41.             /div>  <  
  42.             /div>  <  
  43.             /div>   
  44.   
  45.         <  
  46.         /div>  <  
  47.         /div>   
  48.         @section scripts  
  49.   
  50.         {  
  51.             @Scripts.Render("~/bundles/jqueryval")  
  52.         }  
Step 6 - Don't forget this step. Add these lines in "Web.config" file. Use this code inside "<appseting>".
  1. <appSettings>  
  2.     <add key="ClientValidationEnabled" value="true" />  
  3.     <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
  4. </appSettings>  
Step 7 -This step is also important because without adding "jquery.validate" and "jquery.validate.unobtrusive"  this library works in background, which needs to be added in "bundle.config" file. Use the code, given below-
  1. using System.Web;  
  2. using System.Web.Optimization;  
  3.   
  4. namespace RemoteValidation {  
  5.     public class BundleConfig {  
  6.         // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862   
  7.         public static void RegisterBundles(BundleCollection bundles) {  
  8.             bundles.Add(new StyleBundle("~/Content/css").Include(  
  9.                 "~/Content/css/bootstrap.css",  
  10.                 "~/Content/css/font-awesome.css",  
  11.                 "~/Content/css/site.css"));  
  12.   
  13.             bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
  14.                 "~/Scripts/jquery-{version}.js"));  
  15.   
  16.             bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
  17.                 "~/Scripts/jquery.validate*"));  
  18.         }  
  19.     }  
  20. }  
Step 8 - Now, set your "route.config" default controller and an action according your Application and run. If you have configured all the settings and implemented the code properly and followed all steps, you can see output screen, as shown below-

default controller

According to this image, you can see that I am typing "Bikesh". It is showing an error message "Employee name already exists" because I have written the hard-coded "Bikesh" in the model.

There are two situations to check Validation. 
  1. You can check only Employee Name.
  2. You can check both conditions, "Employee Name" and Email Id.

I hope, you understood all the things about "Remote validation". You can also download the project and run it on your system.