2

我目前正在使用淘汰赛验证对表单进行验证,如下所示:

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();}}});
}

目前,当 IsMarried 复选框被选中时,配偶字段将不会正确验证,直到输入值然后清除。

有什么方法可以根据事件修改我的淘汰视图模型上的绑定,或者使验证更快发生?

4

1 回答 1

5

您可以使用 ko.validation.group 或 ko.validatedObservable,它使您能够检查错误并手动触发验证。

这是您可以解决此问题的一种方法:

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 for invalid properties
        houseHold.errors.showAllMessages();
    }
    //it looks like you need to 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>

工作 jsfiddle 示例。

那么这段代码做了什么:

  • 开始验证 keydown 上的文本输入
  • 在复选框单击时触发验证
于 2013-09-03T21:52:54.017 回答