Remote Validation in MVC


Hi everybody, here in this article I will explain how to implement the remote validation in MVC. Remote validation is the process where we validate specific data posting data to a server without posting the entire form data to the server. Let's see an actual scenario, in one of my projects I had a requirement to validate an email address, whether it already exists in the database. Remote validation was useful for that; without posting all the data we can validate only the email address supplied by the user.

Practical Explanation

Let's create a MVC project and name it accordingly, for me its “TestingRemoteValidation”. Once the project is created let's create a model named UserModel that will look like:

  1. public class UserModel  
  2. {
  3.     [Required]
  4.     public string UserName { getset; }
  5.     [Remote("CheckExistingEmail","Home",ErrorMessage = "Email already exists!")]
  6.     public string UserEmailAddress { getset; }
  7. }

Let's get some understanding of the remote attribute used, so the very first parameter “CheckExistingEmail” is the name of the action. The second parameter “Home” is referred to as controller so to validate the input for the UserEmailAddress the “CheckExistingEmail” action of the “Home” controller is called and the third parameter is the error message. Let's implement the “CheckExistingEmail” action result in our home controller.

  1. public ActionResult CheckExistingEmail(string UserEmailAddress)
  2. {
  3.     bool ifEmailExist = false;
  4.     try
  5.     {
  6.         ifEmailExist = UserEmailAddress.Equals("") ? true : false;
  7.         return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);
  8.     }
  9.     catch (Exception ex)
  10.     {
  11.         return Json(false, JsonRequestBehavior.AllowGet);
  12.     }
  13. }

For simplicity I am just validating the user input with a hard-coded value ( but we can call the database and determine whether or not the given input exists in the database.

Let's create the view using the defined “UserModel” and using the create scaffold template; the UI will look like:


We will get the following output if we use “” as UserEmailAddress:

I hope this will help.