开发者

regex pattern for delete, arrows and escape keys

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.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开发者_JAVA技巧 examples.

I have tested this using my laptop keyboard and an external full size keyboard.

Edit 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

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


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).

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.com/js/key.html. It will tell everything you need to know to solve this.

A summary:

  • You'll need to use the keydown (not keypress) 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 the which property.
  • keyCode has no relation to the character typed in keydown and keyup, 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 (not keydown), so to support Opera, you'll need to handle the keypress event as well, and set a flag in the keydown event for the keypress handler to check.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜