Reputation:
I am trying to validate a text box to allow all positive numbers including -1 in it.
i tried this, which will work for allowing only positive numbers
function allownumbers(e, txtBox) {
var key;
key = (e.keyCode) ? e.keyCode : e.charCode;
if (e.charCode == 0) {
return true;
}
if ((key < 48 || key > 57) && (key != 46) && (key != 44)) {
return false;
}
if (key == 46) {
if ((txtBox.value).indexOf('.') != -1) {
return false;
}
}
if (key == 44) {
if ((txtBox.value).indexOf(',') != -1) {
return false;
}
}
return true;
}
But how to allow -1(only) with all positive numbers Thanks in advance
Upvotes: 0
Views: 1347
Reputation: 7253
Instead of preventing keystrokes, why not validate and sanitize the input? Maybe something like this:
function allownumbers(e, txtBox) {
var val = parseInt(txtBox.value);
if(!val || val < -1) {
val = 0; // invalid value, reset to zero
}
txtBox.value = val;
}
Upvotes: 1