I was looking for an easy way to implement a validation based on the result of an AJAX request without making it synchronous. I noticed that Knockout JS Validation wraps it’s calls to validation functions in a computed observable. This means our validation result will be dynamically re-evaluated if we base it on another observable.
The trick is to create an observable into which we feed the result of the HTTP call-back, and use that in the validation function. Here’s a code snippet using JQuery too, it assumes there’s a service that checks that the field value is unique and returns true or false.
var viewModel = {
myField: ko.observable(null),
isMyFieldUnique: ko.observable(true)
};
viewModel.myField.subscribe(function () {
$.getJSON(
'myservice?myField=' + escape(viewModel.myField(),
function (result) {
viewModel.isMyFieldUnique(result);
}
);
});
viewModel.myField.extend({
validation: {
validator: function (val, param) {
return viewModel.isMyFieldUnique();
},
message: "myField is not unique."
}
});
We’re hosting a Code Club community training evening to allow anyone who is thinking of becoming a Code Club volunteer an opportunity to find out more about Code Club and get an insight into what to expect and how to…
Discover MoreThis year saw the launch of a new service from Leeds-based start-up RaceBest Ltd. NewRedo were responsible for building their online system and we continue to host and support it. In building the system we utilised some of the latest…
Discover MoreWe’ve just published an early working version of an on-line service created by NewRedo, however, although written in ASP.NET MVC 2, it’s not running on a Microsoft server. Instead we’re running on Ubuntu 11.10 using the NGINX web server. First,…
Discover More