有一个快速的方法来设置HTML文本输入(<input type=text />),只允许数字击键(加上'.')?


当前回答

我对于更好的用户体验的解决方案:

超文本标记语言

<input type="tel">

jQuery

$('[type=tel]').on('change', function(e) {
  $(e.target).val($(e.target).val().replace(/[^\d\.]/g, ''))
})
$('[type=tel]').on('keypress', function(e) {
  keys = ['0','1','2','3','4','5','6','7','8','9','.']
  return keys.indexOf(event.key) > -1
})

细节:

首先,输入类型:

数字显示的上下箭头缩小了实际的输入空间,我发现它们很丑,只有当数字表示一个数量时才有用(比如电话、区号、id……)不需要) Tel提供类似的没有箭头的数字浏览器验证

使用[number / tel]也有助于在移动设备上显示数字键盘。

对于JS验证,我最终需要2个函数,一个用于正常的用户输入(按键),另一个用于复制+粘贴修复(更改),其他组合会给我一个糟糕的用户体验。

我使用更可靠的KeyboardEvent。key代替现在已弃用的KeyboardEvent.charCode

根据你的浏览器的支持,你可以考虑使用Array.prototype.includes()而不是名字不好的Array.prototype.indexOf() (true / false结果)

其他回答

正则表达式和匹配函数可以很好地处理这种情况。例如,我使用下面的代码来验证图上作为坐标的4个输入框。它运行得相当好。

function validateInput() {
   if (jQuery('#x1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null || 
       jQuery('#x2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null || 
       jQuery('#y1').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null ||
       jQuery('#y2').val().toString().match(/^[-]?[0-9]+[\.]?[0-9]*$/) == null) {
         alert("A number must be entered for each coordinate, even if that number is 0. Please try again.");
         location.reload();
   }
}

当涉及到万无一失的用户体验时,人们应该总是尝试保持一个“用户智力”的参考点。

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方法慢几微秒。

优点: 假设用户有基本的阅读和理解知识,

高度可定制的选项。 工作跨浏览器和独立于语言。 利用表单中已有的功能来显示错误和警告。

2个解决方案:

使用表单验证器(例如jQuery验证插件)

在输入字段的onblur事件期间(即当用户离开字段时)执行检查,使用正则表达式:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>

请记住地区差异(欧洲人使用句点和逗号的方式与美国人相反),加上负号(或将数字用括号括起来表示负数的习惯),加上指数符号(我正要谈到这个)。

更安全的方法是检查输入的值,而不是劫持按键并试图过滤keycode。

通过这种方式,用户可以自由使用键盘箭头、修改键、退格键、删除键、使用非标准键键、使用鼠标粘贴、使用拖放文本,甚至使用辅助输入。

下面的脚本允许正数和负数

1
10
100.0
100.01
-1
-1.0
-10.00
1.0.0 //not allowed

var input = document.getElementById('number'); 输入。Onkeyup =输入。onchange = enforcfloat; //强制只能输入浮点数 函数enforceFloat() { Var valid = /^\-?\d+\. d*$|^\-?[\d]*$/; var = / \ \ d + \数量。* | \ \ d - (\ d) * | (\ d) + \ \ [d]。* | (\ d) + /; If (!valid.test(this.value)) { Var n = this.value.match(number); 这一点。Value = n ?N[0]:“; } } <input id="number" value="-3.1415" placeholder="Type a number" autofocus> .

编辑:我删除了我的旧答案,因为我认为它现在已经过时了。