如何根据事件更改敲除验证

时间:2013-09-03 19:37:23

标签: knockout.js knockout-validation

我目前正在使用knockout validation对表单进行验证:

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复选框时,配偶字段将不会正确验证,直到输入一个值然后清除。

有什么方法可以根据事件修改我的knockout viewmodel上的绑定,或者让验证更快地发生?

1 个答案:

答案 0 :(得分: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>

Working jsfiddle sample.

这段代码的作用是什么:

  • 开始验证keydown上的文本输入
  • 触发复选框点击
  • 上的验证