简体   繁体   English

我只想在 html 输入字段中允许使用数字和正斜杠

[英]I want to allow only numbers and forward slash in a html input field

I want to allow only numbers and the forward slash character using the pattern attribute in my input field我只想在我的输入字段中使用模式属性允许数字和正斜杠字符

  1. You can use this website to get the keyCode: http://keycode.info/你可以使用这个网站来获取keyCode: http : //keycode.info/
  2. 0-9 keyCodes are '48'-'57'. 0-9 keyCodes 是'48'-'57'。 Forward slash's keyCode is 191.正斜杠的 keyCode 是 191。

 function validateNumberAndForwardSlash(event) { var key = window.event ? event.keyCode : event.which; if (event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 191) { return true; } else { return false; } };
 <input type="text" onkeypress="return validateNumberAndForwardSlash(event);">

PS This is a keyCode summary article: https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes PS 这是一篇keyCode总结文章: https : //www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

function isNumber(evt) {
    evt = (evt) ? evt : window.event;
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode !== 47) 
    {
        return false;
    }
    return true;
}

You should not listen for keyboard events ( keydown / keypress / keyup ) to filter out certain characters, as the value of the input can also be updated by pasting or dropping text into it and there are many exceptions you should not prevent, such as arrows, delete, escape, shortcuts such as select all, copy, paste... so trying to come up with an exhaustive list of the ones that should be allowed is probably not a good idea.您不应该监听键盘事件( keydown / keypress / keyup )来过滤掉某些字符,因为输入的值也可以通过将文本粘贴或拖放到其中来更新,并且有许多您不应该阻止的异常,例如箭头、删除、转义、诸如全选、复制、粘贴之类的快捷方式……因此尝试列出应允许的所有内容的详尽列表可能不是一个好主意。

Instead, just listen for the input event and update the input value removing all invalid characters while preserving the cursor's position:相反,只需侦听input事件并更新输入值,删除所有无效字符,同时保留光标的位置:

 const input = document.getElementById('input'); input.oninput = (e) => { const cursorPosition = input.selectionStart - 1; const hasInvalidCharacters = input.value.match(/[^0-9/]/); if (!hasInvalidCharacters) return; // Replace all non-digits: input.value = input.value.replace(/[^0-9/]/g, ''); // Keep cursor position: input.setSelectionRange(cursorPosition, cursorPosition); };
 <input id="input" type="text" placeholder="Digits and forward slash only" />

Here you can see a similar answer and example for a slightly more complex behaviour to allow only numbers with one single decimal separator: https://stackoverflow.com/a/64084513/3723993在这里,您可以看到一个类似的答案和示例,用于稍微复杂的行为,仅允许带有一个小数分隔符的数字: https : //stackoverflow.com/a/64084513/3723993

If someone is nowadays looking for the answer (like I was), the simplest and obvious one is (at least from today's perspective) missing.如果现在有人正在寻找答案(就像我一样),那么最简单和明显的答案就是(至少从今天的角度来看)不见了。 Additionally, I think this is also the one which was actually asked for.此外,我认为这也是实际要求的那个。 Namely, the use of the pattern attribute of the HTML input field.即,使用 HTML 输入字段的 pattern 属性。

To allow only digits and slashes as requested, an input field with the following pattern can be used:要按要求仅允许数字和斜杠,可以使用具有以下模式的输入字段:

<input type="text" pattern="[0-9/]*" title="Please enter only numbers or slashes!">

The title is displayed in many browsers as a hint to the user if his input does not match the pattern.如果用户的输入与模式不匹配,标题会在许多浏览器中显示,作为对用户的提示。 If the input of at least one character is required, the pattern "[0-9/]+" can be used instead (and the input field should be set to be required).如果需要输入至少一个字符,可以使用模式"[0-9/]+"代替(输入字段应设置为必填)。

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

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