Demo number

by Stephen

HTML

<!-- Here is a number input -->
<input type="number" max=9999 min="-9999" pattern="-?[0-9]{0,11}" id="my-input">
<!-- Here is a text input -->
<input type="text">

<!-- They both look the same with CSS -->

CSS

/* Just remove the arrows in CSS */
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

input {
  min-width: 200px;
}

input:invalid {
    border-color: red;
}

JavaScript

let myInput = document.getElementById("my-input");
let myInputValue = myInput.value;
let regex = new RegExp(/(^\-?[0-9]{0,11}$)/);

myInput.addEventListener("input", (e)=>{
    e.preventDefault();
    if (regex.test(myInput.value))
    {
      console.log("Change value", myInput.value, "to", myInputValue);
      myInputValue = myInput.value;
    } 
    else 
    {
      myInput.value = myInputValue;
    }
});