mint
mint

Reputation: 3433

Javascript RegEx for Numbers Only (no special characters)

I'm trying to find a RegEx that will allow the digits 0-9 ONLY and not special characters. Is this an impossibility since pressing Shift + 2 is still a digit?

I've used the following:

return /[0-9]|\./.test(String.fromCharCode(event.keyCode));

Which works fine except for the special characters that are still allowed.

Any input would be most helpful.

Upvotes: 1

Views: 12540

Answers (4)

Diego
Diego

Reputation: 18349

I think you are in the right track. Just add !event.shiftKey:

return /[0-9]|\./.test(String.fromCharCode(event.keyCode)) && !event.shiftKey;

There are also altKey and ctrlKey if you need them.

For keyCodes coming form the numeric keypad, you need to compare against the numeric keyCode instead of using a Regex:

return (/[0-9]|\./.test(String.fromCharCode(event.keyCode)) && !event.shiftKey) 
    || (event.keyCode >= 96 && event.keyCode <= 105);

This technique can also be used instead of the Regex you are using:

return (event.keyCode >= 48 && event.keyCode <= 57 && !event.shiftKey) 
    || (event.keyCode >= 96 && event.keyCode <= 105);

See http://unixpapa.com/js/key.html

Upvotes: 4

Lucas
Lucas

Reputation: 14909

One problem i see is that keyCode could be multiple digits, but your regex is just one digit followed by a period. Perhaps this:

return /\d+/.test( String.fromCharCode(event.keyCode) );

What are you doing this for?

Upvotes: 0

Brian
Brian

Reputation: 2229

Have you tried this one?

"^[0-9]+$"

Upvotes: 0

Rob I
Rob I

Reputation: 5737

I think /[0-9]/ should work as you say. It will not match "shift-2", only the exact characters 0, 1, 2, ..., 9. I think the |\. part of your RE is what's hurting you...

Upvotes: 0

Related Questions