Reputation: 1833
I don't understand strange knockout-validation async validator behavior. If I work with other observable in the this validator, validation process becomes endless. Please, look jsFiddle example. If I remove string 4, 5 or 8, it will work correct.
ko.validation.rules.asyncValidator = {
async: true,
validator: function (val, vm, callback) {
vm.bar();
vm.bar(true);
setTimeout(function () {
console.log('validating ...');
vm.bar(false);
callback(true);
}, 1000);
}
};
ko.validation.registerExtenders();
vm = {
foo: ko.observable(),
bar: ko.observable()
};
vm.foo.extend({asyncValidator: vm});
ko.applyBindings(vm);
Upvotes: 1
Views: 375
Reputation: 619
KnockoutValidation subscribes to change events on the observables you extend in order to run the validation method when the value changes. Because you are changing the value of the observable inside it's own validation method, you are getting an infinite loop.
Basically, you cannot assign a value to the thing you are validating inside of the validation method.
Upvotes: 1
Reputation: 2254
I doubt it is a good idea to change model values in the validation process. You should never do it, knockout or not knockout. I do not know how the validation internally works but it probably uses the same mechanism as the computed: evaluating which observables you read in the function, to be able to call the validator only when these observables change. That would explain why you do not get an infinite loop when you do not read bar. And the reason why you do not get the infinite loop when you remove the other lines is because the value does not change.
Upvotes: 1