StealthRT
StealthRT

Reputation: 10542

Javascript regex to disable shift, alt and ctrl keys

I am using the following RegEx to disable all but numbers, comma and dot.

function isNumber(evt) {
    var theVal = $(evt).val();
    var theEvent = theVal || window.event;
    var key = theEvent.keyCode || theEvent.which;

    key = String.fromCharCode(key);

    if (key.length == 0) return;
    var regex = /^[0-9.,\b]+$/;

    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault) theEvent.preventDefault();
    }
}

And the HTML code:

<input type="text" id="number" onkeydown="isNumber($(this));" />

It works nicely but if I hold the Shift key down then I am able to input letters and special characters into the box which I do not want the user to be able to do.

What do I need to add to the RegEx above in order to block the Shift, Ctrl and Alt key as well?

Upvotes: 0

Views: 4070

Answers (1)

James Wilkins
James Wilkins

Reputation: 7367

The reason it's not working is because SHIFT is a KEYDOWN event (shiftKey==true and keyCode==0), and when you press another key, a second event is triggered, which is why it is showing the symbols.

If you change the event to onkeypress, it should work.

Also, you don't need jQuery for this at all, see here:

https://jsfiddle.net/1569atLz/1/

Warning: People can still copy-n-paste into the edit box (unless you check for any change and not just key presses), so make sure to always validate server side as well when sending data! Anyone can easily press F12 and use the dev tools to force a change.

Upvotes: 6

Related Questions