Reputation: 1203
I know that this question has been asked before, but all solutions that I've seen here had some limitations.
What I'm trying to achieve: I have an input field that should allow entering or pasting only alphanumeric characters, and total length must not exceed N characters. It should work in mobile browsers.
What I have tried so far:
return this.value.length < 8 && (event.keyCode >= 65 && event.keyCode <= 90 || event.keyCode >= 97 && event.keyCode <= 122 || event.keyCode >= 48 && event.keyCode <= 57)
). Doesn't affect pasting and for some strange reason doesn't work at all in Chrome on Android.As far as I know, it is a typical task (CVV codes / card numbers on payment forms, order numbers in e-commerce, etc.), but all solutions have some drawbacks. Seems that I am missing something. Please help.
Upvotes: 9
Views: 27955
Reputation: 1330
Using the validation built into Html5 inputs will prevent non-numeric input when you place the type=number attribute to an input. You could also use the max attribute if you want to set a maximum number to be allowed for entry. You still need to implement some type of client-side code to prevent numbers with older browsers, but the basic Html5 validation does a lot o work for you on any decent "real" browser (Chrome, Firefox, I.E v9+, ect)
Here is documentation on the input type="number"
Upvotes: 0
Reputation: 1634
What about using Input Pattern?
<input type="text" pattern="[A-Za-z]{3}" title="Three letters">
<input type="text" pattern="[0-9]{3}" title="Three numbers">
<input type="text" pattern="[A-Za-z0-9]{3}" title="Three alphanumeric">
combined with something like this answer and this
Upvotes: 11
Reputation: 137
I once needed to do the same thing and I found that the best solution is to have a listener that is called every time the input field changes. For this you should be able to use either the oninput
html attribute or the corresponding input
javascript event.
This demo from W3Schools demonstrates pretty well how it responds to input changes. In particular, it does not only fire when focus is lost and it works when pasting text as well. Naturally, inside the listener you can check that the current text in the input conforms to whatever you want.
What's even cooler with this solution is that you can even edit the text inside the input field from within the listener. For this you need to add the listener to the input
event in javascript using addEventListener(...)
, then just use this.value = 'new text';
.
Upvotes: 0