有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?
当前回答
有一个很好的解决方案。删除前导零,设置自然位和小数点后的最大位数,处理复制粘贴,确保它是一个数值。
this.value = this.value
.replace(/\b0+/g, '')
.replace(/[^0-9.]/g, '')
.replace(/(\..*?)\..*/g, '$1')
.replace(/([0-9]{0,6}(\.[0-9]{0,2})?).*/g, '$1')
最后替换设置小数点和自然位的长度。只需将标记替换为您喜欢的值。
.replace (/ ([0 - 9] {0, < max_natural >} (\ [0 - 9] {0, < max_decimal >}) ?)。* / g, 1美元)
其他回答
当涉及到万无一失的用户体验时,人们应该总是尝试保持一个“用户智力”的参考点。
While neglecting everything other than numbers, a dot and a hyphen would seem like the perfect choice, you should also consider letting them enter any content, and when they're done, purify the input; if not a valid number, show error. This method would make sure no matter what the user manages to do, the result will always be valid. If the user is naive enough not to understand the warnings and error messages, pressing a button and seeing that nothing happens (as in keycode comparison) will only confuse him/her more.
同样,对于表单,验证和错误消息显示几乎是必需的。所以,这些条款可能已经存在了。算法如下:
On losing-focus or form-submission, do following. 1.1. Read content from the input and apply parseFloat to result 1.2. If the result is a Non-accessible-Number (NaN), reset the input field and pop-up an error message: "Please enter a valid number: eg. 235 or -654 or 321.526 or -6352.646584". 1.3. Else, if String(result)!==(content from input), change value of the field to result and show warning message: "The value you entered have been modified. Input must be a valid number: eg. 235 or -654 or 321.526 or -6352.646584". For a field that cannot allow any unconfirmed value, then this condition may be added to step 1.2. 1.4. Else, do nothing.
该方法还为您提供了额外的优势,可以根据最小值、最大值、小数点等执行验证。只需要对步骤1.2之后的结果执行这些操作。
缺点:
输入将允许用户输入任何值,直到焦点丢失或表单提交为止。但如果填写说明足够清楚,90%的情况下可能不会出现这种情况。 如果步骤1.3用于显示警告,则可能会被用户忽略,并可能导致无意的输入提交。抛出错误或正确显示警告可以解决这个问题。 速度。这可能比regex方法慢几微秒。
优点: 假设用户有基本的阅读和理解知识,
高度可定制的选项。 工作跨浏览器和独立于语言。 利用表单中已有的功能来显示错误和警告。
使用这个DOM:
<input type = "text" onkeydown = "validate(event)"/>
还有这个脚本:
validate = function(evt)
{
if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
{
evt.returnValue = false;
if(evt.preventDefault){evt.preventDefault();}
}
}
...或者这个脚本,没有indexOf,使用两个for…
validate = function(evt)
{
var CharValidate = new Array("08", "046", "039", "948", "235");
var number_pressed = false;
for (i = 0; i < 5; i++)
{
for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
{
if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
{
number_pressed = true;
}
}
}
if (number_pressed == false)
{
evt.returnValue = false;
if(evt.preventDefault){evt.preventDefault();}
}
}
我使用onkeydown属性而不是onkeypress,因为onkeydown属性是在onkeypress属性之前检查的。问题出在谷歌Chrome浏览器上。
与属性“onkeypress”,标签将不可控与“preventDefault”谷歌chrome,然而,与属性“onkeydown”,标签变成可控!
9 . TAB =>的ASCII码
第一个脚本的代码比第二个脚本少,但是ASCII字符数组必须包含所有的键。
第二个脚本比第一个脚本大得多,但是数组并不需要所有的键。数组每个位置的第一位数字是每个位置将被读取的次数。对于每一个读数,都将加1到下一个读数。例如: NCount = 0
48 + NCount = 48
NCount + +
48 + NCount = 49
NCount + +
...
48 + NCount = 57 在数字键只有10(0 - 9)的情况下,但如果它们是100万个,那么创建一个包含所有这些键的数组就没有意义了。
ASCII代码:
8 ==>(退格); 46 =>(删除); 37 =>(左箭头); 39 =>(右箭头); 48 - 57 =>(数字); 36 => (home); 35 => (end);
上面的一些答案使用了过时的内容,比如which的使用。
要检查按下的键是否为数字,可以使用keyup eventListener来读取event.key的值。如果不是数字,就不要输入字符。您可以将其他密钥加入白名单。例如,允许用户使用箭头在输入字段中向后或向前导航,或者按退格键并删除输入的数字。
validate (event) {
const isNumber = isFinite(event.key)
const whitelist = ['Backspace','Delete','ArrowDown','ArrowUp','ArrowRight','ArrowLeft']
const whitelistKey = whitelist.includes(event.key)
if (!isNumber && !whitelistKey) {
event.preventDefault()
}
}
您可以尝试使用" 'onkeydown " '事件并取消事件(事件。preventDefault或类似的)当它不是允许的键之一。
这是一个改进的函数:
function validateNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}