Reputation: 87
I'm creating a web form that I'd like to add field verification to. The current approach involved specifying a "pattern" attribute in the input tags as follows:
<input id="foo" class="span7" type="text" pattern="^[0-9]*\.?[0-9]*$">
However, this approach has unexpected behavior, and as I've read from MDN, is not supported in all major browsers. Is there an alternative to this functionality?
To be clear, I'd like to trigger a stylistic effect if the contents of the text box does not match a specified regex. I realize this can be achieved with Jquery and add/remove class, but this feels rather inefficient.
Upvotes: 1
Views: 884
Reputation: 1411
there's really no efficient way to do this; you either need to employ pattern
or do your own event listener which runs its own regex on a key event.
Upvotes: 1
Reputation:
Try this:
HTML:
<input id="foo" class="span7" type="text" onblur="checkInput(this.value,'^[0-9]*\.?[0-9]*$');">
JavaScript:
<script>
function checkInput(txt, pattern) {
var re = new RegExp(pattern);
var x = re.test( txt );
//--- if x != true then show error message
}
</script>
Upvotes: 0