knockout.js - How can I change knockout validation based on an event -
i'm using knockout validation validation on form such:
html
<div> <span>client</span><input type="text" data-bind="value:client" /> </div> <div> <span>ismarried</span><input type="checkbox" data-bind="value:ismarried" /> </div> <div> <span>spouse</span><input type="text" data-bind="value:spouse" /> </div>
js
function household() { var self = this; self.client = ko.observable().extend({required:true}); self.ismarried = ko.observable(); self.spouse = ko.observable().extend({required:{ onlyif:function(){ return self.ismarried();}}}); }
currently, when ismarried checkbox gets checked, spouse field wont validate until value has been entered cleared.
is there way can modify bindings on knockout viewmodel based on event or otherwise make validation happen sooner?
you use ko.validation.group or ko.validatedobservable, enables checking errors , manually trigger validation.
this 1 way resolve this:
js
var household = function(){ var self = this; self.client = ko.observable().extend({required:true}); self.ismarried = ko.observable(); self.spouse = ko.observable().extend({required:{ onlyif:function(){ return self.ismarried();}}}); } var household = new household(); ko.validation.group(household); var forcevalidation = function(){ //is viewmodel valid? if(!household.isvalid()) { //shows error messages invalid properties household.errors.showallmessages(); } //it looks need return true else checkbox doesn't stay checked return true; } var vm = { household: household, forcevalidation: forcevalidation } ko.applybindings(vm);
html
<div> <span>client</span><input type="text" data-bind="value:household.client, valueupdate: 'afterkeydown'" /> </div> <div> <span>ismarried</span><input type="checkbox" data-bind="checked:household.ismarried, click:forcevalidation" /> </div> <div> <span>spouse</span><input type="text" data-bind="value:household.spouse, valueupdate: 'afterkeydown'" /> </div>
so code does:
- starts validating text inputs on keydown
- triggers validation on checkbox click
Comments
Post a Comment