Remote Validation in ASP.NET MVC
The process of validating specific data field by posting it to server without posting the entire form is remote validation.
For e.g : There is a unique field in the database table,it's uniqueness needs to be to checked when client enters data in user input. Posting the entire form for validation takes a lot of time instead validation of unique field is to be checked which is performed by remote validation.
Example to demonstrate remote Validation in MVC :-
Create a model with a unique field to which remote validation is to be applied
public class EmployeeModel
{
[Required]
public string EmployeeName { get; set; }
[Remote("IsEmailUnique","Home",ErrorMessage = "Email already exists!")]
public string EmployeeEmailAddress { get; set; }
}
The remote attribute used in EmployeeModel with EmployeeEmailAddress field has first parameter as action name(IsEmailUnique),second parameter as controller's name(Home) and third parameter as error message.
Implementation of IsEmailUnique action in Home controller :-
public ActionResult IsEmailUnique(string EmployeeEmail)
{
bool ifEmailExist = false;
try
{
ifEmailExist = EmployeeEmail.Equals("deepak@gmail.com") ? true : false;
return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
In above controller action employee email is validated with a hard coded value it can be compared with database values. Whenever user fills the employee input unique field and submits the data if the employee email address is same as"deepak@gmail.com" then an error "Email already exists!" occur.
0 Comment(s)