简体   繁体   中英

Cannot validate dot for input type number

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM