asp.net-mvc Remote validation


Example

Remote Validation used to check whether the content enter in the input control is valid or not by sending an ajax request to server side to check it.

Working

The RemoteAttribute works by making an AJAX call from the client to a controller action with the value of the field being validated. The controller action then returns a JsonResult response indicating validation success or failure. Returning true from your action indicates that validation passed. Any other value indicates failure. If you return false, the error message specified in the attribute is used. If you return anything else such as a string or even an integer, it will be displayed as the error message. Unless you need your error message to be dynamic, it makes sense to return true or false and let the validator use the error message specified on the attribute.

ViewModel

public class ViewModel
{
    [Remote("IsEmailAvailable", "Group", HttpMethod = "POST", ErrorMessage = "Email already exists. Please enter a different email address.")]
    public string Email{ get; set; }
}

Controller

[HttpPost]
public JsonResult IsEmailAvailable(string Email)
{
    // Logic to check whether email is already registered or Not.
    var emailExists = IsEmailRegistered();
    return Json(!emailExists);         
} 

Live Demo Fiddle

You can pass additional properties of the model to the controller method using the AdditionalFields property of RemoteAttribute. A typical scenario would be to pass the ID property of the model in an 'Edit' form, so that the controller logic can ignore values for the existing record.

Model

  public int? ID { get; set; }
  [Display(Name = "Email address")]
  [DataType(DataType.EmailAddress)]
  [Required(ErrorMessage = "Please enter you email address")]
  [Remote("IsEmailAvailable", HttpMethod="Post", AdditionalFields="ID", ErrorMessage = "Email already exists. Please enter a different email address.")]  
  public string Email { get; set; }

Controller

[HttpPost]
public ActionResult Validate(string email, int? id)
{
    if (id.HasValue)
    {
        return Json(!db.Users.Any(x => x.Email == email && x.ID != id);
    }
    else
    {
        return Json(!db.Users.Any(x => x.Email == email);
    }
}

Working Demo - Additional Fields

Additional Note

The default error message is understandably vague, so always remember to override the default error message when using the RemoteAttribute.