2016-01-21 41 views
12

似乎什麼是jQuery.validate的正常使用情況與MDL出了問題。請參閱this gistMDL + jQuery驗證集成:變通需要MDL-radio__button驗證

這工作得很好:

<h1>Without MDL</h1> 
<form id="foo"> 
    <input type="radio" name="bar" value="1" /> 1 
    <input type="radio" name="bar" value="2" /> 2 
<input type="submit" /> 
</form> 
<script> 
    $(function() { 
     $('#foo').validate({ 
      rules: { 
       "bar": { 
        required: true 
       }, 
      }, 
      errorPlacement: function(error, element) { 
       console.log(element); 
      } 
     }); 
    }); 
</script> 

這確實什麼

<h1>With MDL</h1> 
<form id="zha"> 
    <label for="baz__1" class="mdl-radio mdl-js-radio"> 
     <input type="radio" name="baz" value="1" id="baz__1" class="mdl-radio__button" /> 1 
    </label> 
    <label for="baz__2" class="mdl-radio mdl-js-radio"> 
     <input type="radio" name="baz" value="2" id="baz__2" class="mdl-radio__button" /> 2 
    </label> 
    <input type="submit" id="butt"/> 
</form> 
<script> 
    $(function() { 
     $('#zha').validate({ 
      rules: { 
       "baz": { 
        required: true 
       }, 
      }, 
      errorPlacement: function(error, element) { 
       console.log(element); 
      } 
     }); 
    }); 
</script> 

附加jQuery.validator.setDefaults({ debug: true })沒有任何影響 - 在調試輸出 - 在MDL版本。刪除mdl-js-radiomdl-radio__button使其正常工作。我的直覺是,MDL正在更新在斷開jQuery的到name=屬性訪問的方式,DOM,但我無法找到任何證據來支持,在MDL源代碼。

任何人得到了在這裏工作的整合?

+0

報價:*「我的直覺是,MDL正在更新在斷開的方式DOM ......」 *〜這大概就是這樣的;那麼爲什麼不簡單地使用任何瀏覽器的DOM檢測工具,並找出? – Sparky

+0

我做過了,但是我的DOM-fu很弱或者我的直覺錯誤。 – BrianTheLion

+0

它只是一個錯字,你沒有在jquery函數中包裝mdl版本的腳本? – jcuenod

回答

5

經過一番研究,我想我找到了解決您的問題。這是一個有趣的。
對我而言,您的代碼適用於Firefox,但不適用於Chrome和Safari。原因很簡單。 MDL刪除輸入單選按鈕的CSS默認樣式以隱藏它們(不顯示:無,僅高度:0,寬度:0,不透明度...)。 Chrome和Safari認爲,有像「隱藏」。瀏覽jQuery.validate代碼,我意識到輸入單選按鈕從未被發現。 (您的代碼可在Chrome和Safari上使用經典輸入)。爲什麼?因爲如果你看看jQuery.validate的默認設置,你可以看到他忽略了隱藏的輸入。

defaults: { 
    ... 
    ignore: ":hidden", 
    ... 
onfocusin: function(element, event) { 

和過濾功能

elements: function() { 
    var validator = this, 
     rulesCache = {}; 

    // select all valid inputs inside the form (no submit or reset buttons) 
    return $(this.currentForm) 
    .find("input, select, textarea") 
    .not(":submit, :reset, :image, [disabled]") 
    .not(this.settings.ignore) // This line 
    .filter(function() { 
     if (!this.name && validator.settings.debug && window.console) { 
      console.error("%o has no name assigned", this); 
     } 

     // select only the first element for each name, and only those with rules specified 
     if (this.name in rulesCache || !validator.objectLength($(this).rules())) { 
      return false; 
     } 

     rulesCache[this.name] = true; 
     return true; 
    }); 
}, 

爲了防止這種情況只需要添加這段代碼:

jQuery.validator.setDefaults({ 
    ignore: "" 
}); 

這對我的作品。希望對你有效。

+0

好的偵探!我馬上會仔細檢查你的工作。 – BrianTheLion

+0

Tks。最後,這不是什麼大不了的事。希望它對你有所幫助。 – smdsgn