验证ObservableArrays之间的重复数据

时间:2017-10-19 20:48:52

标签: javascript validation knockout.js knockout-mvc

我有一个可观察的数组(通过ajax填充),在验证时,不能在数组中的任何2个或更多可观察数据上具有相同的选择值。

<div id="AttrValidationDiv"></div>
    <table>    
    <!-- ko foreach: AttrsViewModels -->
         <tr>
            <td>
              <select data-bind="options:$root.optionsViewModel, optionsText:'ProductName', optionsValue:'ProductId',value:ServiceGroup, optionsCaption:'Select'"></select>
           </td>
          </tr>
        <!-- /ko -->
    </table>

有没有办法在实时添加/删除验证div时实现此目的?

1 个答案:

答案 0 :(得分:2)

您可以使用计算函数来完成此操作,该函数根据AttrsViewModel中的选定选项检查每个选项。只要选定的选项发生变化,计算将自动重新计算,因为它们是可观察的,并且如果绑定到计算函数,div文本将被更新。

function viewModel(){
  var self = this;
  
  this.optionsViewModel = [
    { ProductId: 1, ProductName: 'product 1' },
    { ProductId: 2, ProductName: 'product 2' },
    { ProductId: 3, ProductName: 'product 3' }
  ];
  
  this.AttrsViewModels = ko.observableArray([
    { ServiceGroup: ko.observable() },
    { ServiceGroup: ko.observable() },
    { ServiceGroup: ko.observable() }
  ]);
  
  this.validations = ko.computed(function(){
    for(var i=0; i<self.optionsViewModel.length; i++){
    	var option = self.optionsViewModel[i];
        var matches = self.AttrsViewModels().filter(function(item){
            return item.ServiceGroup() === option.ProductId;
        });
        if(matches.length >= 2){
      	    return option.ProductName + ' is selected more than once';
        }
    }
    return '';
  });
}
    
ko.applyBindings(new viewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="AttrValidationDiv">
  <span data-bind="text: validations"></span>
</div>
<table>    
    <tbody>
    <!--ko foreach: AttrsViewModels-->
     <tr>
        <td>
          <select data-bind="options:$root.optionsViewModel, optionsText:'ProductName', optionsValue:'ProductId',value:ServiceGroup, optionsCaption:'Select'"></select>
       </td>
    </tr>
    <!--/ko-->
    </tbody>
</table>