验证 ObservableArray 之间的重复数据

Validating Duplicate Data Between ObservableArrays

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

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

有没有办法在 adding/removing 中通过实时验证 div 完成此操作?

您可以使用计算函数来完成此操作,该函数根据您的 AttrsViewModels 中的选定选项检查每个选项。只要选定的选项发生变化,计算就会自动重新计算,因为它们是可观察的,如果绑定到计算函数,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>