Thursday 24 September 2015

MVC5 Client side validation using REMOTE Data annotation

More often we need to do client side validation before we submit the view to the controller. Most of the time , we are using jquery or ajax calls to achieve this objective.

But there is much easier way of achieving this using the remote data annotation in our model class. What it is performing is, invoke an async call to the controller to perform required task.

Following are code samples for this.

1. We need to add following method to the controller which returns JsonResult
 
[HttpPost]
public JsonResult IsPassportExists(string PassportNumber)
{
    return Json(db.Clients.Any(x => x.PassportNumber == PassportNumber), JsonRequestBehavior.AllowGet);
}

2. Following is the corresponding model attribute. Note we are referring the controller's method in this.
 
 [Required]
 [Display(Name = "Passport Number")]
 [StringLength(20)]
 [Remote("IsPassportExists", "Client", HttpMethod = "POST", ErrorMessage = "Passport Number already registered")]
 public string PassportNumber { get; set; }

3. In the View, you just need to refer following js libraries.
 
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

No comments:

Post a Comment