How can I limit possible inputs in a HTML5 "number" element?

And you can add a max attribute that will specify the highest possible number that you may insert

<input type="number" max="999" />

if you add both a max and a min value you can specify the range of allowed values:

<input type="number" min="1" max="999" />

The above will still not stop a user from manually entering a value outside of the specified range. Instead he will be displayed a popup telling him to enter a value within this range upon submitting the form as shown in this screenshot:

enter image description here


You can specify the min and max attributes, which will allow input only within a specific range.

<!-- equivalent to maxlength=4 -->
<input type="number" min="-9999" max="9999">

This only works for the spinner control buttons, however. Although the user may be able to type a number greater than the allowed max, the form will not submit.

Chrome's validation message for numbers greater than the max
Screenshot taken from Chrome 15

You can use the HTML5 oninput event in JavaScript to limit the number of characters:

myInput.oninput = function () {
    if (this.value.length > 4) {
        this.value = this.value.slice(0,4); 
    }
}

If you are looking for a Mobile Web solution in which you wish your user to see a number pad rather than a full text keyboard. Use type="tel". It will work with maxlength which saves you from creating extra javascript.

Max and Min will still allow the user to Type in numbers in excess of max and min, which is not optimal.


You can combine all of these like this:

<input name="myinput_drs"
oninput="maxLengthCheck(this)"
type = "number"
maxlength = "3"
min = "1"
max = "999" />

<script>
  // This is an old version, for a more recent version look at
  // https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/
  function maxLengthCheck(object)
  {
    if (object.value.length > object.maxLength)
      object.value = object.value.slice(0, object.maxLength)
  }
</script>


Update:
You might also want to prevent any non-numeric characters to be entered, because object.length would be an empty string for the number inputs, and therefore its length would be 0. Thus the maxLengthCheck function won't work.

Solution:
See this or this for examples.

Demo - See the full version of the code here:
http://jsfiddle.net/DRSDavidSoft/zb4ft1qq/1/

Update 2: Here's the update code: https://jsfiddle.net/DRSDavidSoft/zb4ft1qq/2/

Update 3: Please note that allowing more than a decimal point to be entered can mess up with the numeral value.


Or if your max value is for example 99 and minimum 0, you can add this to input element (your value will be rewrited by your max value etc.)

<input type="number" min="0" max="99" 
   onKeyUp="if(this.value>99){this.value='99';}else if(this.value<0){this.value='0';}"
id="yourid">

Then (if you want), you could check if is input really number