gpt4 book ai didi

javascript - 使用javascript验证字段中的键输入

转载 作者:行者123 更新时间:2023-11-28 01:05:17 26 4
gpt4 key购买 nike

我正在使用

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

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

我如何才能将其限制为仅在特定输入中提供字符串表示形式的那些键?

最佳答案

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

例如,您可以创建一个数组,其中包含您要忽略的所有键码的列表,并只测试键入的键是否不是其中之一。

这是你需要的:

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 来立即验证每个输入的字符。

关于javascript - 使用javascript验证字段中的键输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40046676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com