简体   繁体   English

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

[英]Validate key input in field with javascript

I am using我在用

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

It almost works.它几乎有效。 The problem is that I cannot use key arrows, backspace, delete, ctrl+a, etc.问题是我不能使用键箭头、退格、删除、ctrl+a 等。

How can I limit it to only those keys that will give a string representation in the specific input?如何将其限制为仅在特定输入中提供字符串表示的那些键?

To ignore those keys you need to add a condition before validating your input.要忽略这些键,您需要在验证输入之前添加条件。

For example you can make an array containing the list of all KeyCodes that you want to ignore and just test if the typed key isn't one of them.例如,您可以创建一个包含要忽略的所有 KeyCode 列表的数组,并测试键入的键是否不是其中之一。

Here's what you need:这是您需要的:

 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">

Note:笔记:

As mentioned in comments you need to use keypress event instead of keyup to validate every inputted character immediately.正如评论中提到的,您需要使用keypress事件而不是keyup来立即验证每个输入的字符。

Well there is somehow to limit your input range.好吧,有某种方式可以限制您的输入范围。 But I think in this case you are looking for a way to identify only printable key events.但我认为在这种情况下,您正在寻找一种仅识别可打印关键事件的方法。

You can achieve this by using the solution proposed by @TimDown on How to detect if the pressed key will produce a character inside an <input> text-box?您可以通过使用@TimDown 提出的解决方案来实现这一点,关于如何检测按下的键是否会在<input>文本框中产生一个字符? applied to a keypress event as you can see on the code below.应用于keypress事件,如下面的代码所示。 So then, you can work just with printable key events.因此,您可以仅使用可打印的关键事件。

 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">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM