我有一个表单的viewmodel,我正在尝试使用knockout-validation添加验证。
<table data-bind='visible: slots().length > 0'>
<thead>
<tr>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
<tbody data-bind='foreach: slots'>
<tr>
<td><input type="text" class="input-medium time-picker" data-bind='value: start_time' required="true"/></td>
<td><input type="text" class="input-medium time-picker" data-bind='value: end_time' required="true"/></td>
<td><a href='#' data-bind='click: $root.removeSlot'><i class="icon-minus-sign"/></a></td>
</tr>
</tbody>
</table>
<button class="btn btn-primary" data-bind='click: addSlot'>Add Row</button>
<table data-bind='visible: slots().length > 0'>
<thead>
<tr>
<th>Start Time</th>
<th>End Time</th>
</tr>
</thead>
<tbody data-bind='foreach: slots'>
<tr>
<td><input type="text" class="input-medium time-picker" data-bind='value: start_time' required="true"/></td>
<td><input type="text" class="input-medium time-picker" data-bind='value: end_time' required="true"/></td>
<td><a href='#' data-bind='click: $root.removeSlot'><i class="icon-minus-sign"/></a></td>
</tr>
</tbody>
</table>
<button class="btn btn-primary" data-bind='click: addSlot'>Add Row</button>
我需要验证,如果我在第1行输入“end_time”,当我添加新行时,第2行的start_time必须大于第1行的end_time。
答案 0 :(得分:0)
如果你想要一个在向数组中添加新项目时不能使用的验证组,你需要使用深度选项。您可以通过将验证组包装在observable中并使用computed来启用禁用保存按钮来解决此问题。
ViewModel = function() {
this.error = ko.observable();
this.items = ko.observableArray();
this.items.subscribe(this.onAdded, this);
this.canSave = ko.computed(this.getCanSave, this);
};
ViewModel.prototype = {
onAdded: function() {
this.error(ko.validation.group(this));
},
add: function() {
this.items.push(new ItemViewModel());
},
getCanSave: function() {
return this.error() && this.error()().length === 0;
}
}