I\'m looking to implement custom client side validation in MVC4. I currently have it working well with the standard attributes, such as this in my model
publ
MVC comes with RemoteAttribute
which internally makes an ajax call to a controller method that returns a Json value indicating if validation succeeded or failed
public JsonResult IsValid(string SourceDirectory)
{
if (someCondition) //test if the value of SourceDirectory is valid
{
return Json(true, JsonRequestBehavior.AllowGet); // indicates its valid
}
else
{
return Json(false, JsonRequestBehavior.AllowGet); // indicates its not valid
// or return Json("A custom error message that overrides the default message defined in the attribute");
}
}
and decorate your property with
[Remote("IsValid", "YourController", ErrorMessage = "The path is not valid")]
public string SourceDirectory { get; set; }
Note: The RemoteAttribute
is only for client side (jquery unobtrusive validation) and you may still need additional server side validation.
Refer How to: Implement Remote Validation in ASP.NET MVC for a detailed example