user3045179
user3045179

Reputation: 331

Input type number maxlength 5

I want to limit the input type number to maximum 5 numbers, I am using below code, which is working well, only issue is that for backspace I have to use event.keycode which I dont want to use. Is there any alternative apart from usking keycode of backspace.

var input = document.getElementById('input');
input.addEventListener('keypress',showData,false)
function showData(event)
{
   if(event.target.value.length<=5)
   {
      return true;
   }
   else
   {
      event.preventDefault();
   }

}

Upvotes: 0

Views: 230

Answers (4)

Niklesh Raut
Niklesh Raut

Reputation: 34914

<form>
<input required type="text" name="inputname" pattern="[0-9]{5,}">
  <input type="submit" value="submit">
</form>

Upvotes: 0

a45b
a45b

Reputation: 519

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

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

Upvotes: 0

user5797159
user5797159

Reputation:

If you want it so if the user tries to type more than 5 numbers it only keeps the 5 numbers:

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

Upvotes: 3

henrikmerlander
henrikmerlander

Reputation: 1574

Why don't you just use:

<input type="number" max="99999">

This will still not stop a user from manually entering a value larger than 99999, but the input element will be invalid.

Upvotes: 0

Related Questions