gpt4 book ai didi

knockout.js - 如何根据事件更改 knockout validation

转载 作者:行者123 更新时间:2023-12-02 04:52:25 24 4
gpt4 key购买 nike

我目前正在使用 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 上的绑定(bind),或者以其他方式使验证更快发生?

最佳答案

您可以使用 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.

那么这段代码做了什么:

  • 开始在按键时验证文本输入
  • 在复选框点击时触发验证

关于knockout.js - 如何根据事件更改 knockout validation ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18600171/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com