Reputation: 341
I've been trying to find a more effective way validate inputs with html5. I have several inputs with the same pattern and so far I've copied an pastad the same pattern in each input.
E.G.:
<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})"/>
I want to do it in such a way that I only have the pattern in one place.
Thanks in advance!
Upvotes: 1
Views: 55
Reputation: 5921
This is not possible with plain html5 but you could use JavaScript or jQuery for that:
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>
Upvotes: 1