I have a large number of text fields that need to be evaluated onkeyup to be sure nothing is entered but numbers. Decimals are ok. So is the absence of a value.
For some reason this is matching on decimals. Eg I type 4 and then . and it flags on .
How do I correct this?
var s_in = 0;
for (var i = 10; i < 19; i++) {
var fObj = document.getElementById(field+'_'+i);
var text = fObj.value;
if (text) {
var s = parseInt(text);
var pattern = /^[+-]?(\d*\.)?\d+$/;
var result;
if ((result = pattern.exec(text)) != null) {
if (s > -1) {
s_in += s;
}
} else { // not empty and not a number
alert('The entry for Hole ' + i + ' ' + ucfirst(field) + ' is "' + text + '" This is not a number. It will be erased now.');
fObj.value = '';
fObj.focus();
return false;
}
}
}
Your regex requires one or more digits after the decimal point and you have to escape the
-in the first group). If you don’t want to require a digit after the decimal, then you can use this (changes a+to a*and puts\in front of the-):