2013-12-21 71 views
0

我正在寫js中的驗證函數。 當我提取邏輯到私有方法時,我的驗證失敗。我找不到原因。爲什麼驗證失敗時提取到方法?

我的HTML確定指標是:

<input type="text" id="searchQuery" data-minlenght="3"> 

此代碼應包含所有的驗證邏輯的任何元素。

我使用下面的行訪問的所有信息:

var query = jQuery("#searchQuery"); 
    cpodesign.Validation.isValid(query, query.val()); 

現在我的驗證的實現是

cpodesign.Validation = (function() { 
      var Settings = { 
       MinLenght: 'minlength', 
      }; 

      //Private members 

      function validateLenght(element, value) { 
       var len = element.data(Settings.MinLenght); 
       return (value.length > len); 
      } 

      return { 
       // public members 
       isValid: function (element, value) { 
        var marginRight = element.data(Settings.MinLenght); 
        if (marginRight !== 'undefined') { 
         return validateLenght(element, value); // does not work 
        } 

        console.error('Validation type not defined'); 
        return true; 
       }, 
      }; 
     })(); 

此實現的工作,但我不知道怎麼做的第一項工作,因爲它的什麼我會比較喜歡。

cpodesign.Validation = (function() { 

      return { 
       // public members 
       isValid: function (element, value) { 
        var marginRight = element.data("minlenght"); 
        if (marginRight !== 'undefined') { 
         return value.length > marginRight; 
        } 

        console.error('Validation type not defined'); 
        return true; 
       }, 
      }; 
     })(); 
+4

拼寫:' MinLenght:'minlength'。所以當你說'element.data(Settings.MinLenght)'時,它不會找到'data-minlenght'屬性。 – nnnnnn

+0

是的,這是問題。不能相信這一點。 – cpoDesign

回答

0

,你會得到一個問題,在IE瀏覽器這個掛乍得耳環

 var Settings = { 
      MinLength: 'minlength', 
     }; 

應該是:

 var Settings = { 
      MinLength: 'minlength' 
     }; 

注:我也糾正你拼寫的「長度」錯誤地幾乎無處不在,除了在屬性值這裏的「使用MINLENGTH」

1

您在HTML中犯了一個錯字。應該是:

<input type="text" id="searchQuery" data-minlength="3">

instaid的:

<input type="text" id="searchQuery" data-minlenght="3">

錯字:data-minlenght