用javascript验证字段中的键输入

Validate key input in field with javascript

本文关键字:输入 字段 javascript 验证      更新时间:2023-09-26

我使用

document.getElementById('input-field').addEventListener('keyup', function (e) {
  if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
    event.preventDefault();
  }
});

它几乎工作。问题是我不能使用箭头键、退格键、删除键、ctrl+a键等。

我怎么能限制它只有那些键,将给出一个字符串表示在特定的输入?

要忽略这些键,您需要在验证输入之前添加一个条件。

例如,你可以创建一个数组,其中包含所有你想忽略的KeyCodes,并且只测试键入的键是否不在其中之一。

这是你需要的:

document.getElementById('input-field').addEventListener('keypress', function(e) {
  //An array of special Keys
  var specialKeys = [37, 38, 39, 40, 8, 13, 27, 46];
  if (specialKeys.indexOf(e.which) === -1) {
    console.log(String.fromCharCode(e.which)+ ' Key is validated!');
    if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
      event.preventDefault();
    }
  }
});
<input type="text" id="input-field" placeholder="input text here">

注意:

正如在注释中提到的,您需要使用keypress事件而不是keyup来立即验证每个输入的字符。

这就限制了你的输入范围。但我认为在这种情况下,您正在寻找一种方法来识别仅可打印的关键事件。

你可以通过使用@TimDown提出的解决方案来实现这一点,如何检测按下的键是否会在<input>文本框内产生一个字符?应用于keypress事件,如下面的代码所示。因此,您可以只处理可打印的键事件。

    function isCharacterKeyPress(evt) {
        if (typeof evt.which == "undefined") {
            // This is IE, which only fires keypress events for printable keys
            return true;
        } else if (typeof evt.which == "number" && evt.which > 0) {
            // In other browsers except old versions of WebKit, evt.which is
            // only greater than zero if the keypress is a printable key.
            // We need to filter out backspace and ctrl/alt/meta key combinations
            return !evt.ctrlKey && !evt.metaKey && !evt.altKey && evt.which != 8;
        }
        return false;
    }
    document.getElementById('input-field').addEventListener('keypress', function (e) {
    	if(isCharacterKeyPress(e)){
            if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
                e.preventDefault();
            }
        }
    });
<input type="text" id="input-field" placeholder="input text here">