【问题标题】:Knockout Validation - How to only validate observables after saving the whole modelKnockout Validation - 如何在保存整个模型后仅验证 observables
【发布时间】:2016-09-25 23:49:13
【问题描述】:
我正在使用Knockout Validation,我真的很难让表单上的字段只有在我对整个模型调用 save 后才能验证。在用户通过表单的那一刻,如果他们输入无效值,错误会立即显示为模糊。
我希望它仅在我单击保存按钮后显示,然后在用户之后进行更改时重新评估每个字段。
下面是我的模型的简化版本。
var model = ko.validatedObservable({
sellingPrice: ko.observable().extend({
min:0
})
});
function Save(){
if(!model.isValid()){
if (model.errors().length > 0) {
model.errors.showAllMessages(true);
}
return false;
} else {
//save the model
}
}
我应该在某个地方设置一个标志来推迟验证,直到整个模型在我的保存方法中得到验证?
【问题讨论】:
标签:
knockout.js
knockout-validation
【解决方案1】:
您可以尝试使用验证组:
看看我写的这个小提琴,我还没有测试过,但它应该能让你了解它是如何工作的。
https://jsfiddle.net/xggu9Lv2/47/
var ViewModel = function() {
var self = this;
// Declare
self.sellingPrice = ko.observable(null);
self.otherThing = ko.observable(null);
self.anotherThing = ko.observable(null);
self.Validator = ko.observable(null);
// Set validation rules
self.setValidation();
self.setValidation = function() {
self.sellingPrice.extend({
min: 0
})
self.otherThing.extend({
required: true
})
self.anotherThing.extend({
required: true
})
//Validation group
self.FieldValidator = ko.validation.group({
sellingPrice: self.sellingPrice,
otherThing: self.otherThing,
anotherThing: self.anotherThin
});
}
self.save = function() {
// Check the length of the validation group
if (!this.Validator().length) {
// All is OK!
}
}
};
ko.applyBindings(new ViewModel());
【解决方案2】:
我必须查看更多代码以了解验证的使用方式,但是当我查看 the docs 时,我认为您需要做的就是更仔细地查看您是如何呈现验证的错误。
您应该能够使用可见性或隐藏绑定来包装包含错误的 div,该可见性或隐藏绑定绑定到您在保存方法中明确设置的其他可观察对象,并且验证失败。
另一种选择是创建您自己的验证对象,该对象公开您绑定到的自己的错误可观察对象。我们在我工作的地方这样做 - 如果您有兴趣了解它的结构,请发表评论,我可以提供一个简短的概述,但我觉得它有点笨重,并且与 KO 验证背道而驰。