Jul 29, 2015

Remote Validation in MVC

Remote validation is used to make server calls to validate data without posting the entire form to the server when server side validation is preferable to client side.  It's all done set up model and controller which is pretty neat.  
Suppose if any field in database table that must be unique and we want to check this uniqueness on client side(after text change of text-boxes) instead of posting whole page.

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, whetehr 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:
public class UserModel
{   
    [Required]
    public string UserName { get; set; }
    [Remote("CheckExistingEmail","Home",ErrorMessage = "Email already exists!")]
    public string UserEmailAddress { get; set; }
}
Let's get some understanding of the remote attribute used, so the very first parameter “CheckExistingEmail” is the 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.
public ActionResult CheckExistingEmail(string UserEmailAddress)
{
    bool ifEmailExist = false;
    try
   {
        ifEmailExist = UserEmailAddress.Equals("mukeshknayak@gmail.com") ? true : false;              
        return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);
    }
   catch (Exception ex)
   {               
       return Json(false, JsonRequestBehavior.AllowGet);
    }
}
For simplicity I am just validating the user input with a hard-coded value (mukeshknayak@gmail.com) 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 “mukeshknayak@gmail.com” as UserEmailAddress:



No comments:

Post a Comment