2013-10-10 86 views
1

我有一個視圖模型,我試圖添加驗證來使用敲除驗證。 嵌套數據結構中的敲除驗證

<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」當我比排START_TIME添加新行2必須比END_TIME行1

回答

0

你需要使用選項很深,如果也更大你想有一個驗證組,當向數組添加新項目時不起作用。您可以通過將驗證組包裝在可觀察對象中來解決該問題,並使用計算來啓用禁用保存按鈕。

http://jsfiddle.net/vGTCz/2/

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; 
    } 
}