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


当前回答

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

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

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

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

其他回答

上面的一些答案使用了过时的内容,比如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()
  }
}

使用这个正则表达式/\D*/g

const phoneHandler = (event: React.ChangeEvent<HTMLInputElement>) =>{
setPhone(event.target.value.replaceAll(/\D*/g, ''));};

下面的代码还将检查PASTE事件。 取消“ruleSetArr_4”的注释,并在“ruleSetArr”中添加(concate)以允许浮点数。 简单的复制/粘贴功能。用参数中的input元素调用它。 例如:inputIntTypeOnly($('输入[name = " inputName "] '))

function inputIntTypeOnly(elm){ elm.on("keydown",function(event){ var e = event || window.event, key = e.keyCode || e.which, ruleSetArr_1 = [8,9,46], // backspace,tab,delete ruleSetArr_2 = [48,49,50,51,52,53,54,55,56,57], // top keyboard num keys ruleSetArr_3 = [96,97,98,99,100,101,102,103,104,105], // side keyboard num keys ruleSetArr_4 = [17,67,86], // Ctrl & V //ruleSetArr_5 = [110,189,190], add this to ruleSetArr to allow float values ruleSetArr = ruleSetArr_1.concat(ruleSetArr_2,ruleSetArr_3,ruleSetArr_4); // merge arrays of keys if(ruleSetArr.indexOf() !== "undefined"){ // check if browser supports indexOf() : IE8 and earlier var retRes = ruleSetArr.indexOf(key); } else { var retRes = $.inArray(key,ruleSetArr); }; if(retRes == -1){ // if returned key not found in array, return false return false; } else if(key == 67 || key == 86){ // account for paste events event.stopPropagation(); }; }).on('paste',function(event){ var $thisObj = $(this), origVal = $thisObj.val(), // orig value newVal = event.originalEvent.clipboardData.getData('Text'); // paste clipboard value if(newVal.replace(/\D+/g, '') == ""){ // if paste value is not a number, insert orig value and ret false $thisObj.val(origVal); return false; } else { $thisObj.val(newVal.replace(/\D+/g, '')); return false; }; }); }; var inptElm = $('input[name="inputName"]'); inputIntTypeOnly(inptElm); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" name="inputName" value="1">

这里的大多数答案都有使用关键事件的缺点。

许多答案会限制你使用键盘宏进行文本选择、复制+粘贴和更多不必要的行为,其他的似乎依赖于特定的jQuery插件,这是用机关枪杀苍蝇。

这个简单的解决方案似乎最适合我跨平台,不管输入机制(击键,复制+粘贴,右键单击复制+粘贴,语音到文本等)。所有文本选择键盘宏仍然可以工作,它甚至会限制通过脚本设置非数字值的能力。

function forceNumeric(){
    var $input = $(this);
    $input.val($input.val().replace(/[^\d]+/g,''));
}
$('body').on('propertychange input', 'input[type="number"]', forceNumeric);

下面是我喜欢使用的一个很好的简单的解决方案:

function numeric_only (event, input) {
    if ((event.which < 32) || (event.which > 126)) return true; 
    return jQuery.isNumeric ($(input).val () + String.fromCharCode (event.which));
}// numeric_only;

<input type="text" onkeypress="return numeric_only (event, this);" />

解释:

使用“事件。-首先确定它是否是一个可打印字符。如果不是,那么允许它(如删除和退格)。否则,将字符连接到字符串的末尾,并使用jQuery的“isNumeric”函数测试它。这样就避免了测试每个角色的单调乏味,也适用于剪切/粘贴场景。

如果你想变得更可爱,那么你可以创建一个新的HTML输入类型。让我们称它为“numeric”,这样你就可以有这样的标签:

<input type="numeric" />

它只允许数字字符。只需添加下面的“文档”。准备好”命令:

$(document).ready (function () {
    $("input[type=numeric]").keypress (function (event) {
        if ((event.which < 32) || (event.which > 126)) return true; 
        return jQuery.isNumeric ($(this).val () + String.fromCharCode (event.which));
    });// numeric.keypress;
});// document.ready;

HTML并不关心你使用的类型名称-如果它不识别它,那么它将默认使用一个文本框,所以你可以这样做。你的编辑可能会抱怨,但这就是问题所在。毫无疑问,清教徒会抓狂,但它很有效,很简单,到目前为止对我来说还很强大。

更新

这里有一个更好的方法:它考虑到文本选择,并使用本地javascript:

verify (event) {
    let value = event.target.value;
    let new_value = `${value.substring (0, event.target.selectionStart)}${event.key}${value.substring (event.target.selectionEnd)}`;
    if ((event.code < 32) || (event.code > 126)) return true;
    if (isNaN (parseInt (new_value))) return false;
    return true;
}// verify;