Is is possible to change the attribute valueUpdate from "onblur" to "keyup" depending on if the attribute has an error attached?
I want to mimick the way validation is done in jQuery Validation, and first do validation on blur, and afterwards do validation on keyup.
Is this possible?
EDIT: Let me just clarify and give an example. I do not mind that binding to the model occurs on "keyup", what I do mind is that the user is shown an error message, before even given the chance to finish typing. Instead, if I take example in validating an email address. If the user types in an invalid email I would like the error to show on blur, and if the user puts focus on the field again to correct the error I would like the error to disappear once the error is corrected. On the other hand, if the user types in a valid email to begin with, and later introduces an error, the error should show immediately.
SECOND EDIT: So I've given it some thought, and I believe that the validation shouldn't interfere with model binding, instead the changes should be made to the displaying of error messages. As stated, I would like the error to appear immediately after the error occurs, but only after a change event happened on the relevant field.
I made this fiddle that almost works, but it should show exactly what I'm trying to accomplish.
http://jsfiddle.net/mntm1bne/3/
<div data-bind="validationOptions: {messageTemplate: 'myCustomTemplate'}">
<input data-bind="value: firstName, valueUpdate: 'keyup', event: {change: firstName.enableD}" />
<br />
<input data-bind="value: lastName" />
<div data-bind="if: firstName.isD">
Firstname is dirty!
</div>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
<div data-bind="text: ko.toJSON($data)"></div>
</div>
<script type="text/html" id="myCustomTemplate">
<span data-bind="visible: field.isD && !field.isValid(), attr: { title: field.error }">X</span>
</script>
ko.extenders.trackChange = function(target, track) {
if (track) {
target.isD = ko.observable(false);
target.enableD = function() {
console.log("enable!");
target.isD(true);
}
}
return target;
};
var ViewModel = function () {
var self = this;
self.firstName = ko.observable().extend({ trackChange: true, required: { message: "firstName" }, number: true,
min: 0,
max: 100
});
self.lastName = ko.observable().extend({ required: { message: "lastName" }});
}
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
Specifically, the error lies in the first validation message, that is shown on page load.