2014-09-24 52 views
0

我有一個場景,當我動態地添加多行使用template方式我需要寫下驗證如果CountryCode(應該是唯一的)在兩個或多個動態生成的行中具有相同的值。如何進行驗證以查找重複條目?剔除

工作小提琴http://jsfiddle.net/JL26Z/73/

好吧,我想這可以使用自定義的驗證碼是可能的,但我不知道如何繼續我的意思是如何在validator功能比較裏面validation

同樣可以通過點擊submit保存功能來完成,就像我們運行一個foreach每個aganist每行code並且這樣做,但這是一個很好的做法。

我的視圖模型:

function Phone() { 
     var self = this; 
     self.Code = ko.observable(""); // this should be unique 
     self.Date = ko.observable(""); 
     self.PhoneNumber = ko.observable(""); 

     self.Validation = ko.validatedObservable([ 
      self.Code.extend({ required: true }), 
      self.Date.extend({ required: true }), 
      self.PhoneNumber.extend({ required: true }) 
     ]); 
     } 

    function PhoneViewModel() { 
     var self = this; 
     self.PhoneList = ko.observableArray([new Phone()]); 
     self.remove = function() { 
      self.PhoneList.remove(this); 
     }; 
     self.add = function() { 

      self.PhoneList.push(new Phone()); // i add on click of add button 
     }; 
    } 

    ko.applyBindings(new PhoneViewModel()); 

任何建議表示讚賞。

+0

請不要在外部網站上保留屬於您問題的整個代碼。在這裏複製它,保持鏈接到jsFiddle。 – Tomalak 2014-09-24 10:36:16

+1

tomalak建議採取。謝謝 – 2014-09-24 11:55:53

回答

1

首先,在您的設置:

// straight from https://github.com/Knockout-Contrib/Knockout-Validation 
ko.validation.rules['mustEqual'] = { 
    validator: function (val, otherVal) { 
     return val === otherVal; 
    }, 
    message: 'The field must equal {0}' 
}; 

後來,在PhoneViewModel

self.codesAreUniuqe = ko.computed(function() { 
    var codes = {}, 
     valid = true; 

    // group by code, count occurrences 
    ko.utils.arrayForEach(self.PhoneList(), function (phone) { 
     var code = phone.Code(); 
     codes[code] = codes[code] ? codes[code] + 1 : 1; 
     valid = valid && codes[code] === 1; 
    }); 

    return valid; 
}).extend({ mustEqual: true }); 
+0

有點困惑,我擔心我會面臨一些範圍問題類似於我以前未回答的帖子http://stackoverflow.com/questions/25994704/how-to-access-outer-function-observable-in-inner-function-in -viewmodel – 2014-09-24 13:49:07

+0

範圍問題?我不知道你的意思。 – Tomalak 2014-09-24 13:50:58

+0

看到我需要對我的函數Phone()中的每一行應用驗證到一個可觀察的'代碼',如果我應用計算器,如你在電話功能中提到的,我不能訪問'self.PhoneList'它給了我undefined 。 – 2014-09-24 13:54:29

1

添加下面的jQuery在$(document).ready(function(){});,它會告訴你重複的文本字段:

$(document).ready(function() { 
    $("input:submit").click(function() { 
     $("input:text").each(function(){ 
      var index = $(this).index("input:text") % 3; 
      var value = $(this).val(); 
      $("input:text").not(this).each(function(){ 
       if($(this).index("input:text") % 3 == index && $(this).val() == value && $(this).val()!="") 
        $(this).next().show().text("Repeated"); 
      }); 
     }); 
    }); 
}); 

DEMO(與你的小提琴)。

+0

真棒,你的努力是讚賞,但無論如何,我需要以'ko'方式處理事情。任何想法 – 2014-09-24 13:50:30

+1

不是真的,從來沒有使用過這個框架。可以幫助您純JavaScript/jQuery。 :) – 2014-09-24 14:25:56