javascript 用于删除、箭头和转义键的正则表达式模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7226402/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regex pattern for delete, arrows and escape keys
提问by Jamex
I am writing a javascript code to restrict the keys that can be entered into a text box.
我正在编写一个 javascript 代码来限制可以输入到文本框中的键。
function keyRestricted(e) {
var keypressed;
var keychar;
var keycheck;
// IE - keyCode
// Netscape/Firefox/Opera - which
keypressed = e.keyCode || e.which;
keychar = String.fromCharCode(keypressed);
//alert(keychar);
keycheck = /[a-zA-Z0-9\b]/;
return keycheck.test(keychar);
} //keyrestricted
my regex is now /[a-zA-Z0-9\b]/
, which allows alphanumeric and backspace. I want to allow the delete, L/R arrows, and escape keys to work in firefox (3.6).
我的正则表达式现在是/[a-zA-Z0-9\b]/
,它允许字母数字和退格。我想允许删除、L/R 箭头和转义键在 Firefox (3.6) 中工作。
I am not sure sure what are the symbols for these keys.
我不确定这些键的符号是什么。
In ie8, the escape key (and del/arrows) still is active even if the \e switch is excluded from the regex, when pressed, it resets/empties the text box.
在 ie8 中,即使 \e 开关从正则表达式中排除,转义键(和 del/箭头)仍然处于活动状态,按下时,它会重置/清空文本框。
In FF, I put the escape in the expression /[a-zA-Z0-9\b\e]/
, but it does not seem to work for firefox, that is when the escape key is pressed, it does not reset/empty the text box.
在 FF 中,我将转义符放在表达式中/[a-zA-Z0-9\b\e]/
,但它似乎不适用于 Firefox,即当按下转义键时,它不会重置/清空文本框。
what are the valid symbol for the regex to allow alphanumeric, L/R arrows, delete, escape?
正则表达式允许字母数字、L/R 箭头、删除、转义的有效符号是什么?
Also, what is the translation for this [a-zA-Z0-9\-\_]
?
It was meant to be alphanumeric and hyphens. But what is the slash infront of the hyphen since hyphen does not need a slash? and what is the \_
for since the underscore is not matched by the expression?
另外,这个的翻译是[a-zA-Z0-9\-\_]
什么?它应该是字母数字和连字符。但是由于连字符不需要斜线,所以连字符前面的斜线是什么?什么是\_
因为下划线与表达式不匹配?
TIA
TIA
Edit
编辑
The reason why using keycode numbers as suggested by nnnnn did not work for me (for other people?) is because the keycodes from 65-90 are for uppercase letters, even though some websites do claim that those keycodes work for both lower and upper cases.
使用 nnnnn 建议的键码数字对我(对其他人?)不起作用的原因是因为 65-90 的键码用于大写字母,即使某些网站确实声称这些键码适用于小写和大写.
This http://www.lookuptables.com/website shows that lowercase letters are from 97-122. Unfortunately, this range has some unmapped overlaps with some characters. For example, the \ character is listed as having 220 keycode. But my filter to deactivate of keycodes > 122 would still allow the \ to get through. There are other examples.
这个http://www.lookuptables.com/网站显示小写字母来自 97-122。不幸的是,这个范围与某些字符有一些未映射的重叠。例如,\ 字符被列为具有 220 键码。但是我的停用键代码 > 122 的过滤器仍然允许 \ 通过。还有其他例子。
I have tested this using my laptop keyboard and an external full size keyboard.
我已经使用我的笔记本电脑键盘和外部全尺寸键盘对此进行了测试。
Edit 2
编辑 2
I have combined both the regex and the keycode arguments into one function. The function works in principle, but due to crazy keycode conflicts, it does not work for the % sign. It requires both the onkeydown and onkeypress to catch all the keys (except the % key). See my discussion herejavascript regex for key event input validations troubleshooting help
我已将正则表达式和键码参数组合成一个函数。该函数原则上有效,但由于疯狂的键码冲突,它不适用于 % 符号。它需要 onkeydown 和 onkeypress 来捕获所有键(% 键除外)。请参阅我在此处的讨论javascript regex 以获取关键事件输入验证故障排除帮助
<head>
<script type="text/javascript">
function keyRestricted(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
var keychar = String.fromCharCode(key);
//alert(keychar);
var keycheck = /[a-zA-Z0-9]/;
// backspace || delete || escape || arrows
if (!(key == 8 || key == 27 || key == 46 || key == 37 || key == 39)) {
if (!keycheck.test(keychar)) {
theEvent.returnValue = false; //for IE
if (theEvent.preventDefault) theEvent.preventDefault(); //Firefox
}
}
}
</script>
</head>
<body>
Please modify the contents of the text field.
<input
type="text" value=""
onKeypress="return keyRestricted(event)"
onKeydown="return keyRestricted(event)"
/>
</body>
回答by nnnnnn
As far as I know, Regex - or at least the JavaScript version - doesn't let you test for some of those "special" characters like escape and the arrow keys (though I believe you can test for backspace).
据我所知,Regex - 或者至少是 JavaScript 版本 - 不允许您测试某些“特殊”字符,例如转义符和箭头键(尽管我相信您可以测试退格键)。
I prefer to implement this sort of thing with a standard if
statement:
我更喜欢用标准if
语句来实现这种事情:
var keypressed = e.which || e.keyCode;
if ((keypressed >=65 && keypressed <= 90) // letters
|| (keypressed >=48 && keypressed <= 57) // digits
|| keypressed === 8 // backspace
|| keypressed === 27 // escape
|| keypressed === 46 // delete
|| (keypressed >= 35 && keypressed <= 40) // end, home, arrows
// TODO: shift, ctrl, alt, caps-lock, etc
) {
// do something
}
// If the keys you care about don't follow any particular pattern
// a switch might be more convenient:
switch (keypressed) {
case 8:
case 27:
case 46:
// valid key, do something
break;
default:
// invalid key, do something else
break;
}
// You can also do something like this:
var permittedKeyCodes = {
"8" : true, // backspace
"27" : true, // escape
"46" : true // delete
};
if (permittedKeyCodes[keypressed]) {
// do something
}
If you use the latter approach, it would be more efficient to define the permittedKeyCodes
object outside your function.
如果使用后一种方法,则在permittedKeyCodes
函数外部定义对象会更有效。
There are various places (here's one) where you can get a list of all of the keycodes.
有很多地方(这里是一个),您可以在其中获得所有键码的列表。
Note that if you're trapping the keydown or keyup event the keycodes returned are associated with the keys, not the characters, so e.g., upper and lowercase A both have the same code. The keypress event works differently.
请注意,如果您正在捕获 keydown 或 keyup 事件,则返回的键码与键相关联,而不是与字符相关联,因此例如,大写和小写 A 都具有相同的代码。keypress 事件的工作方式不同。
回答by Tim Down
Just read through http://unixpapa.com/js/key.html. It will tell everything you need to know to solve this.
只需通读http://unixpapa.com/js/key.html 即可。它会告诉你解决这个问题需要知道的一切。
A summary:
总结:
- You'll need to use the
keydown
(notkeypress
) event to detect non-printable keys such as arrow keys - The
keyCode
property of the event will then work in all browsers, so there's no need for thewhich
property. keyCode
has no relation to the character typed inkeydown
andkeyup
, so do not attempt to obtain a character from the event.- Opera only allows you to suppress the default browser behaviour in the
keypress
event (notkeydown
), so to support Opera, you'll need to handle thekeypress
event as well, and set a flag in thekeydown
event for thekeypress
handler to check.
- 您需要使用
keydown
(notkeypress
) 事件来检测不可打印的键,例如箭头键 keyCode
事件的属性随后将在所有浏览器中工作,因此不需要该which
属性。keyCode
与键入的字符keydown
和没有关系keyup
,因此不要尝试从事件中获取字符。- Opera 只允许您在
keypress
事件中抑制默认浏览器行为(而不是keydown
),因此为了支持 Opera,您还需要处理该keypress
事件,并在keydown
事件中设置一个标志以供keypress
处理程序检查。