限制小数,只允许数字

Restrict decimal and allowing only number

我正在尝试通过限制小数来验证只允许数字的文本字段,但由于某些原因它也接受小数。

<input type="text" id="textbox" maxlength="10" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '');"></input>

这样做:

*Javascript 为必填项

将只允许数字和返回 space 键

<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />

现在检查

<input type="text" oninput="this.value = this.value.replace(/[^0-9]/, '')" />

您的原始解决方案很接近 - 如果您只是从第一个 replace:

的否定匹配中删除 .,则第二个 replace 不是必需的
<input type="text" id="textbox" maxlength="10" oninput="this.value = this.value.replace(/[^0-9]/g, '');"></input>