我正在使用这个插件
https://github.com/ericmbarnard/Knockout-Validation,我试图验证一个动态加载的对象.
使用Javascript:
function VM() { var self = this; // This is a static observable,just to ensure that basic validation works fine. self.static = ko.observable(); self.static.extend({required: true}); // This is the observable that will be updated to my model instance. self.person = ko.observable({}); // This is an handler for manual trigger. // I'm not even sure this is needed. self.a = function(){ self.errors.showAllMessages(); self.staticErrors.showAllMessages(); } // Here i'm loading current person from somewhere,i.e. a rest service. self.load = function() { // Update observable self.person(new Model()); // Define validation rules self.person().name.extend({required: true}); self.person().email.extend({required: true}); // Set person data self.person().name('Long'); self.person().email('John'); // Set validators self.errors = ko.validation.group(self.person); self.staticErrors = ko.validation.group(self.static); } } // Just a test model. function Model() { this.name = ko.observable(); this.email = ko.observable(); } ko.validation.init(); var vm = new VM(); ko.applyBindings(vm);
<ul> <li>1. Hit "Load"</li> <li>2. Hit "Show errors",or maunally change input data.</li> </ul> <button data-bind='click: load'>Load</button> <br/> <h1>This is working properly.</h1> <input type='text' data-bind='value: static' /> <br/> <h1>This is not working.</h1> <input type='text' data-bind='value: person().name' /> <input type='text' data-bind='value: person().email' /> <br/> <button data-bind='click: a'>Show errors</button>
我该如何使这项工作?
解决方法
验证插件仅在您的绑定中应用,只有当Knockout解析绑定时,您的属性才会生效.
用不同的单词:在UI上绑定该属性之后,您无法向属性添加验证.
在你的例子中,你在self.person = ko.observable({})中使用一个空的对象;作为默认值,因此当Knockout执行data-bind =’value:person().name’表达式时,您没有name属性,因此即使以后将name属性添加到对象中,验证也将不起作用.
在您的示例中,您可以通过更改Model构造函数来解决此问题,以包括验证规则:
function Model() { this.name = ko.observable().extend({required: true}); this.email = ko.observable().extend({required: true}); }
并使用一个空的Model对象作为默认的人:
self.person = ko.observable(new Model());
self.load = function() { // Set person data self.person().name('Long'); self.person().email('John'); }
演示JSFiddle.
注意:如果将整个对象替换为self.person(new Model()),Knockout并不总是很好处理;所以无论如何,一个更好的做法是只更新属性,而不是丢弃整个对象.
一个不同的解决方案是使用with绑定,因为在绑定绑定KO将重新评估绑定,如果绑定的属性改变.
所以改变你的看法:
<!-- ko with: person --> <input type='text' data-bind='value: name' /> <input type='text' data-bind='value: email' /> <!-- /ko -->
在这种情况下,您需要使用null作为默认的人:
self.person = ko.observable();
在您的加载中,您需要在分配您的人员属性之前添加验证,以便KO应用您的属性具有验证的绑定:
self.load = function() { var model = new Model() model.name.extend({required: true}); model.email.extend({required: true}); self.person(model); // Set person data self.person().name('Long'); self.person().email('John'); }
演示JSFiddle.