[英]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.12
和10.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: 它的作用如下:
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.