Reputation: 402
There is an input field on the JSP where users can enter numbers(negative and positive both). I've a JS function that checks on each key up event on the input field is not a number, it should replace it with blank.
var txt = $(elem).val();
if(!(txt.match(/^-?[0-9]*$/))) {
$(elem).val(txt.replace(/^-?[0-9]+/g, ''));
}
My if condition is working fine, but I'm not able to create a regex for replacing.
Upvotes: 0
Views: 1235
Reputation: 4824
To check if a number do this
var txt = $(elem).val();
if (!isNAN(txt) && parseInt(txt) >=0) {
//validate
} else {
// Invalidate
}
Upvotes: 1
Reputation: 36511
Edit: question was clarified that only numeric values should be accepted
You could just check that the number is < 0
after removing all non-numeric characters:
// remove all non-numeric characters
var txt = $(elem).val().replace(/[^\-0-9]/g, '');
if(parseInt(txt) < 0)){
// negative number
}
Upvotes: 5