I am using a onKeyDown and a regular expression to parse keyboard input. I need it to all A-Z, backspace, and question mark. The problem es with the ?, I cannot get it to be accepted. I have tried
/[A-Z\x08?]/
/[A-Z\x08\?]/
/[A-Z\x08\\?]/
/[A-Z\x08\x3F]/
None of which allow the ? to be accepted.
function kd(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[A-Z\x08]/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
Any help would be greatly appreciated.
I am using a onKeyDown and a regular expression to parse keyboard input. I need it to all A-Z, backspace, and question mark. The problem es with the ?, I cannot get it to be accepted. I have tried
/[A-Z\x08?]/
/[A-Z\x08\?]/
/[A-Z\x08\\?]/
/[A-Z\x08\x3F]/
None of which allow the ? to be accepted.
function kd(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[A-Z\x08]/;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
Any help would be greatly appreciated.
Share Improve this question asked Dec 26, 2012 at 0:51 Vincent JamesVincent James 1,1583 gold badges17 silver badges27 bronze badges2 Answers
Reset to default 3The question mark should go inside the character class:
/[A-Z\x08?]/
Another problem is that you should be using onkeypress
to determine which character was typed. The onkeyup
and onkeydown
events only tell you which keys were pressed and released, but they don't say what characters these correspond to. On different keyboards you have to press different keys to generate the same character.
For example on my keyboard I have to press Shift and + to get a ?
. On a US keyboard you typically have to press Shift and / to get ?
. Because of this difference in keyboard layouts it is unreliable to use the onkeyup and onkeydown events to detect ?
.
If you want to prevent printing char in textbox when the reg matches, you should use keypress. And the reg is: /^[a-zA-Z\x08\?]$/
. This works for me.
var regex = /^[a-zA-Z\x08\?]$/;
// OR this one if you want uppercase letters:
var regex = /^[A-Z\x08\?]$/;
$("#regtest").keypress(function(event) {
var _event = event || window.event;
var key = _event.keyCode || _event.which;
alert(key);
key = String.fromCharCode(key);
alert(key);
if(regex.test(key)) {
_event.returnValue = false;
if (_event.preventDefault)
_event.preventDefault();
}
});