1

I am trying to add validation for input type number to accept only integer. I added pattern="\d*" to the element. It works fine for input 10.12, 10.13. But fails for input 10.

I printed the value for the html input. It is 10 instead of 10..

<script>
    function getValue(){
        alert(document.getElementById("numberInput").value);
    }   
</script>   

<input type="number" id="numberInput"> </input>
<button onclick="getValue();">

Ideally it should consider 10. as invalid input.

lumio
  • 7,428
  • 4
  • 40
  • 56
Eshita Mathur
  • 43
  • 1
  • 1
  • 7
  • Please provide a [minimal, complete and verifiable example](https://stackoverflow.com/help/mcve). Where is your pattern? Where is your validation function? – lumio Oct 22 '18 at 07:54
  • Issue here is "10." is considered as 10 for input type integer. – Eshita Mathur Oct 22 '18 at 07:55
  • Possible duplicate of [How to avoid Decimal values in input type number](https://stackoverflow.com/questions/37043867/how-to-avoid-decimal-values-in-input-type-number) – lumio Oct 22 '18 at 08:01
  • The solutions provided to restrict characters on keypress will work fine. But not in case if someone copy and paste "10." to input type number. – Eshita Mathur Oct 22 '18 at 08:09

1 Answers1

0

Pasting is indeed tricky. I came up with the following:

function setValid(target) {
  const val = target.value;
  // Remove value, as setting the same value has no effect.
  target.value = '';
  // Reset value on the next tick
  requestAnimationFrame(() => target.value = val);
}
<form action="#" method="post">
  Numbers: <input name="num"
                  type="number"
                  min="1"
                  step="1"
                  onblur="setValid(this)"
                  onpaste="requestAnimationFrame( () => setValid(this) )"
                  onkeypress="return event.charCode >= 48 && event.charCode <= 57"
                  title="Numbers only">
  <input type="submit">
</form>

What this does is the following:

  1. When the input loses focus, it resets the value
  2. When pasting, it waits until the value is set, and then resets it.

There are probably even better solutions out there.

This answer is based on kneeki's answer here.

lumio
  • 7,428
  • 4
  • 40
  • 56