Introduction
In Knockout, we can use custom validation to validate our view models. But sometimes, we may need to examine validation from server end. Here, we will demonstrate how we can use Knockout validation with jquery Ajax and server end calling.
Background
For a quick preview, check out http://jsfiddle.net/FkxKK/.
To perform this example, we are using libraries like:
- jquery-2.1.1.js
- knockout-3.1.0.js
- knockout.validation.js
- jquery.mockjax.js to mock our Ajax calls, which is an exciting library to use for Ajax mocking
Using the Code
First, we will use a custom validation rule with index 'userNameUsed
' like this:
val
indicates the value binded from the HTML DOM, and otherVal
what value we expected to be. $.when
ensures synchs Ajax call, and waits inside the scope until the Ajax call is finished. IsUsed
is returned from the server, indicating if the used name is already used or not (or compared to your preferred returned object or its property.)
ko.validation.rules['userNameUsed'] = {
validator: function (val, otherVal) {
var isUsed;
var json = JSON.stringify({ userName: val });
$.when(
$.ajax({
url: '/validation/IsUserNameUsed',
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: json,
async: false,
})
).then(function (data, textStatus, jqXhr) {
isUsed = (textStatus === 'success') ? data.IsUsed : null;
});
return isUsed === otherVal;
},
message: 'This user name is already in use'
};
ko.validation.registerExtenders();
Use this validation rule into our view model like this, with other validation rules:
self.userName = ko.observable('').extend({ required: true, userNameUsed: false });
as we have assigned userNameUsed: false
in the view model, means we are expecting the result is to be false
.
- If validator Ajax calls
data.IsUsed
returns false
, no error message would be shown. - If Ajax call fails or
data.IsUsed
returned true
, error message would be shown.
We will find two test cases at Scripts/mock.validationPage.js to mimic our Ajax call as we are not using any real server. Uncomment at least one to test if the validation is working or not.
It would be better if we use Ajax validations after basic validations like required, min, max, ... etc.