Vincent James
Vincent James

Reputation: 1148

Regular Expression in Javascript to parse input onKeyDown

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

Upvotes: 1

Views: 11005

Answers (2)

Mark Byers
Mark Byers

Reputation: 838376

The 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 ?.

Upvotes: 3

amiry jd
amiry jd

Reputation: 27585

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();
    }
});

Upvotes: 2

Related Questions