I am writing a javascript code to restrict the keys that can be entered into a text box.
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).
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.
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.
what are the valid symbol for the regex to allow alphanumeric, L/R arrows, delete, escape?
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?
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.
This / 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.
I have tested this using my laptop keyboard and an external full size keyboard.
Edit 2
I have bined 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
<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>
I am writing a javascript code to restrict the keys that can be entered into a text box.
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).
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.
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.
what are the valid symbol for the regex to allow alphanumeric, L/R arrows, delete, escape?
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?
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.
This http://www.lookuptables./ 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.
I have tested this using my laptop keyboard and an external full size keyboard.
Edit 2
I have bined 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
<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>
Share
Improve this question
edited May 23, 2017 at 12:07
CommunityBot
11 silver badge
asked Aug 29, 2011 at 5:26
JamexJamex
1,2225 gold badges23 silver badges34 bronze badges
9
-
Is it mandatory to use a regexp? Simply checking
keypressed
against the codes of delete etc. would be more straight-forward. – pimvdb Commented Aug 29, 2011 at 5:33 -
The keycodes for all of the keys can be found here. In your function, what's the point of your
else if(e.which)
? Ife.which
is not defined your code just carries on anyway withkeypressed
undefined, which probably isn't what you intend. (But on the other hand if you're sure thate.which
will be defined then why theif
?) – nnnnnn Commented Aug 29, 2011 at 5:34 - I have tried the other methods that have been shown on this site. They don't seem to work/behave the way that I intend for my script to work. This method works best, but I need those switches for those keys. – Jamex Commented Aug 29, 2011 at 6:13
-
See my answer below. It gives you some reliable ways to do this without using regular expressions. Note though that I wouldn't remend doing it at all: you're usually better off validating the field
onchange
,onblur
oronsubmit
, unless you have a rock-solid way to stop the user pasting and/or drag'n'dropping invalid characters (and if you do you're the only one). In any case don't forget you'll have to validate it again server-side anyway. – nnnnnn Commented Aug 29, 2011 at 6:19 - Example, the keycode for right arrow is 39, what does that translate to in regex switch? – Jamex Commented Aug 29, 2011 at 6:21
2 Answers
Reset to default 10As 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).
I prefer to implement this sort of thing with a standard if
statement:
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.
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.
Just read through http://unixpapa./js/key.html. It will tell everything you need to know to solve this.
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.