Sunday 18 September 2016

Limit typing numbers in input type 'number' HTML

Recently I have started front-end development using AngularJS where I had the following requirement:
  1. Open a modal window.
  2. Paint form on the modal.
  3. Form will have a text field of type "number" with following criteria:
    1. User can put only positive numbers in the text field nothing else.
    2. User can put numbers only from 0-999.
At first above requirement seems to be very easy to implement with min and max properties of input type "number". However there is a catch that min and max restricts only the spinner (increase and decrease) but user can still type numbers which does not belong to 0-999 (Even characters).

To address first criteria we can use onkeypress event and pass it a function which will listen to 0-9 number key presses only and discard the rest:

onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"

To address second criteria we can use oninput event and pass it a function which will clip/remove the characters after 3rd position:

oninput="this.value.length > 3 ? this.value= this.value.slice(0,3) : this.value"

Note: I have seen suggestions of an alternate approach to accomplish the above using onkeydown event however I have found that if we use onkeydown event it screws up the spinner and also allows text to be pasted and dragged having length more than 3 characters whereas oninput handles all these cases.

Following is the complete input tag:
<input type="number"
       name="sampleTextbox"
       min="0"
       max="999"
       oninput="this.value.length > 3 ? this.value= this.value.slice(0,3) : this.value"
       onkeypress="return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"/>