I am using the following RegEx to disable all but numbers, ma 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?
I am using the following RegEx to disable all but numbers, ma 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?
Share Improve this question edited Jun 2, 2015 at 9:16 David 3,4223 gold badges38 silver badges47 bronze badges asked Apr 23, 2015 at 14:19 StealthRTStealthRT 10.6k41 gold badges194 silver badges363 bronze badges 3-
3
do you have an excellent reason for not using
<input type="number">
like any sane developer would think in this situation? – Touffy Commented Apr 23, 2015 at 14:24 - 1 You'd be surprised how plicated it can be to achieve what you want. Instead of re-inventing the wheel, I'd suggest using an existing plugin that already covers all the edge cases you'll run into: github./SamWM/jQuery-Plugins/tree/master/numeric – laurent Commented Apr 23, 2015 at 14:26
-
Why
isNumber($(this));
and notisNumber(event);
? – James Wilkins Commented Apr 23, 2015 at 16:04
1 Answer
Reset to default 6The 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/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.