简体   繁体   English

无法验证输入类型编号的点

[英]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. 我在元素中添加了pattern="\\d*" It works fine for input 10.12 , 10.13 . 它对于输入10.1210.13 But fails for input 10. 但是输入10.失败10.

I printed the value for the html input. 我打印了html输入的值。 It is 10 instead of 10. . 它是10而不是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. 理想情况下,应将10.视为无效输入。

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 . 该答案基于此处的kneeki答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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