1

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!

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.