我在用
document.getElementById('input-field').addEventListener('keyup', function (e) {
if (!String.fromCharCode(e.which).match(/[A-Za-z0-9,]/)) {
event.preventDefault();
}
});
它几乎可以正常工作。问题是我无法使用键箭头,退格键,删除键,Ctrl + a等。
如何将其限制为仅在特定输入中提供字符串表示形式的那些键?
要忽略这些键,您需要在验证输入之前添加条件。
例如,您可以创建一个数组,其中包含要忽略的所有KeyCode的列表,并仅测试键入的键是否不是其中之一。
这是您需要的:
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
立即验证每个输入的字符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句