Javascript Regex To Limit Text Field To Only Numbers (must Allow Non-printable Keys)
Solution 1:
The best method here is to use input
event which handles all your concerns. It is supported in all modern browsers. With jQuery you can do like following. Handles all cases pasting the value with mouse/keyboard backspace etc.
$('.numeric').on('input', function (event) {
this.value = this.value.replace(/[^0-9]/g, '');
});
See it here
You can check if input
event is supported by checking if the input has this property if not you can use onkeyup
for older browsers.
if (inputElement.hasOwnProperty('oninput')) {
//bind input
} else {
//bind onkeyup
}
Solution 2:
A nice solution is described in a previous post:
jQuery('.numbersOnly').keyup(function () {
this.value = this.value.replace(/[^0-9\.]/g,'');
});
Solution 3:
Try it like,
CSS
.error{border:1px solid #F00;}
SCRIPT
$('#key').on('keydown',function(e){
var deleteKeyCode = 8;
var backspaceKeyCode = 46;
if ((e.which>=48 && e.which<=57) ||
(e.which>=96 && e.which<=105) || // for num pad numeric keys
e.which === deleteKeyCode || // for delete key,
e.which === backspaceKeyCode) // for backspace// you can add code for left,right arrow keys
{
$(this).removeClass('error');
returntrue;
}
else
{
$(this).addClass('error');
returnfalse;
}
});
Fiddle:http://jsfiddle.net/PueS2/
Solution 4:
Instead of checking for the event keyCode, why don't you just check for changes inside the actual input and then filter out non-numbers?
This example uses keyup so that it can read what was actually entered, which means the character is briefly displayed and then removed, but hopefully you get my gist. It might even give the user feedback that the character is not allowed. Either way I think this is the easiest setup, let me know if you need more help fleshing this out.
function filterNonDigits(evt)
{
varevent = evt || window.event;
var val = event.target.value;
var filtered = val.replace(/[^0-9]/g, '');
if(filtered !== val) {
event.target.value = filtered;
event.target.className += " error";
}
}
(jquery used solely to easily bind the keyup function, you won't need it for your actual script)
Solution 5:
/\d/
is equivalent to the above described /[0-9]/
. src: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-digit
Post a Comment for "Javascript Regex To Limit Text Field To Only Numbers (must Allow Non-printable Keys)"