While limiting input length of text box by maxlength property, how to explicitly handle the event that the max length has been exceeded?

StackOverflow https://stackoverflow.com/questions/8868813

  •  28-10-2019
  •  | 
  •  

Frage

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.

War es hilfreich?

Lösung

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:

  • first example: if the value is to long, it will be cut and for one second an error message will be shown; a small disadvantage is that you can see the input in a fraction of a second.
  • in the second example the value will never be changed, an error message will be shown until the number of characters is correct and you can only submit the form if all fields are valid.

=== UPDATE ===

For IE7 and IE8 support I have updated the examples:

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top