My purpose is to limit the user input (which is free text) inside a simple HTML text box to 5 characters. I am using the input field's maxlength property to ensure that, but I need to display a popup when the user tries to type more than 5 characters.
I tried to handle keydown events, but then an ugly if-else would have to be put in order to not take into consideration del,enter,F1..F12, Alt,Page Dn, etc...as all these are allowed, but they don't contribute to the text's length Their keycodes are also not in one sequence. I tried to handle it on keyup, but the character is already typed by that time, and the user sees the extra character disappearing.. not something I want.
A pre-HTML5 solution.. something that would work on IE7,8 would be very useful.
In gecko (e.g. firefox) the browser prevents that the value becomes longer if you use the maxlength
attribute, so the tooLong
validation variable will ever be false
(see here). There is no chance to hook there.
But you can use the pattern
-attribute instead:
<input ... pattern="^.{0,max}$" />
Replace max
in the pattern
regex with the number of maximum allowed characters.
Now you can bind the input
-event and check the boolean element.validity.patternMismatch
if the value is to long.
Here are links to two examples I've created for you; they are tested with the current versions of firefox and chrome, I can't test with IE9:
=== UPDATE ===
For IE7 and IE8 support I have updated the examples: