Saturday 26 September 2015

MVC5 jquery client side unique validation - onblur

I have described how to do client side validation using data annotations using remote attribute in one of my previous posts. This post is about how to use pure jquery with Ajax to do unique validation in a MVC5 web app.

1. First of all, we need to implement a public method in our controller.


 
[HttpPost]
public JsonResult IsPassportExists(string passportNumber)
{
     return Json(db.Clients.Any(x => x.PassportNumber == passportNumber), JsonRequestBehavior.AllowGet);
}

This would do the server side query and do the validation. Note that we are going to return a JsonResult in order to support client side Ajax call.

2. Client side function to perform the server call.
 
 function CheckValue(ctrl) {
            $.ajax({
                url: '@Url.Action("IsPassportExists", "Client")',
                type: 'POST',
                dataType: 'json',
                cache: false,
                data: { 'passportNumber': ctrl.value },
                success: function (value) {
                    if (value) {
                        ctrl.style.backgroundColor = "red";
                        alert('Passport Number already exist!');
                        
                    } else {
                        ctrl.style.backgroundColor = "white";
                    }
                },
                error: function () {
                    alert('Error occured');
                }
            });
        }

We are passing the client controller (ie: textbox) to the function and do the background color change according to the validation result.

3. Finally , following is the way we can call to this function in the textbox
 
 @Html.TextBoxFor(m => m.PassportNumber, new {@class = "form-control", data_bind = "value: PassportNumber", maxlength = "20", onblur = "CheckValue(this)"})

No comments:

Post a Comment