Remote Validation in MVC

Introduction

Hi everybody, here in this article I will explain how to implement remote validation in MVC. Remote validation is the process where we validate specific data by 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 an 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 name of the action. The second parameter “Home” is referred to as the 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("[email protected]") ? 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 ([email protected]) 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 this.

Create scaffold template

We will get the following output if we use “[email protected]” as UserEmailAddress.

output

I hope this will help.


Similar Articles