仅正整数的 HTML 输入(类型=数字) [英] HTML input for Positive Whole Numbers Only (Type=number)
问题描述
我找不到合适的正则表达式模式,尽管这类问题有很多.
I can't find the right regex pattern for this, even though there are a lot of questions in this kind.
我不希望用户能够输入或输入
I dont want the user to be able to type or input
<td><input type="number" pattern=" 0+.[0-9]*[1-9][0-9]*$" name="itemConsumption" /></td>
- -1.0(负值)
- 字符串值和任何字符
- 1.0(十进制值)
- 无范围限制
我只想接受正整数
已解决不需要正则表达式,我不知道这一点:D
SOLVED no need for regex, I did not know this :D
<td><input type="number" pattern=" 0+.[0-9]*[1-9][0-9]*$" name="itemConsumption" onkeypress="return event.charCode >= 48 && event.charCode <= 57"</td>
推荐答案
要禁止除数字以外的任何输入,您可以使用
To disallow any input but numeric, you may use
<input type="text" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" name="itemConsumption" />
^------------....
<form id="mfrm">
<table>
<tr>
<td>Enter number only: <input type="text" name="itemConsumption" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" /></td>
<td><input type="Submit"/></td>
</tr>
</table>
这里,event.charCode == 8 ||event.charCode == 0 ||event.charCode == 13
条件处理按下 DELETE、BACKSPACE 或 ENTER 键的情况(对 Firefox 很重要,请参阅 Mohit 的评论 下面和datashaman 的评论与启用 ENTER 键有关).
Here, the event.charCode == 8 || event.charCode == 0 || event.charCode == 13
condition handles the case when DELETE, BACKSPACE or ENTER keys are pressed (important for Firefox, see Mohit's comment below and datashaman's comment related to enabling the ENTER key).
event.charCode >= 48 &&event.charCode <= 57
表示只返回 0(十进制代码 48)和所有其他直到 9(十进制代码 57)的数字.
The event.charCode >= 48 && event.charCode <= 57
means that only 0 (decimal code 48) and all other digits up to 9 (decimal code 57) will be returned.
这篇关于仅正整数的 HTML 输入(类型=数字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!