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.
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 keyCode
s 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);
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...
你试过这个吗?
"^[0-9]+$"
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?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.