2017-07-13 44 views
1

我一直在試圖找到一種更有效的方法來驗證html5輸入。我有幾個輸入具有相同的模式,到目前爲止,我已經在每個輸入中複製了一個pastad相同的模式。html5在不同的輸入中驗證相同的模式

例如爲:

<input type="text" id="foo1" name="bar1" pattern="([a-z]{2}[0-9]{2})"/> 
<input type="text" id="foo2" name="bar2" pattern="([a-z]{2}[0-9]{2})"/> 
<input type="text" id="foo3" name="bar3" pattern="([a-z]{2}[0-9]{2})"/> 
... 
<input type="text" id="fooN" name="barN" pattern="([a-z]{2}[0-9]{2})"/> 

我想這樣做,以這樣的方式,我只需要在一個地方的模式。

提前致謝!

回答

1

這是不可能的純HTML5,但你可以使用JavaScript或jQuery的爲:

的JavaScript

<script> 
    var input_fields = document.getElementsByTagName('input'); 
    for(var i = 0; i < input_fields.length; i++) { 
     if(input_fields[i].type.toLowerCase() == 'text') { 
      input_fields[i].setAttribute('pattern', '([a-z]{2}[0-9]{2})'); 
     } 
    } 
</script> 

jQuery的

<script> 
    $('text').attr('pattern', '([a-z]{2}[0-9]{2})'); 
</script> 
相關問題