I know there have been a lot of post, blog article answer on Stack Overflow (but the validation does return true
on a tab character) about this. But I'm still looking for a neat way to validate if a value is a number
.
I wrote the following. Does that cover the 99% of the cases? Is there a better way to do that?
function validateNumber(valueToCheck){
var checkSum = 0;
var isValid = true;
if(typeof valueToCheck === "number"){
return true;
}
if(typeof valueToCheck === "string"){
if(valueToCheck.replace(/ /g,'') !== valueToCheck){
return false;
}
if(valueToCheck.charAt(0) == '-'){
valueToCheck = valueToCheck.substr(1); // remove minus sign
}
valueToCheck = valueToCheck.replace('.',''); // allow one decimal point
}
for(var i=0;i<valueToCheck.length; i++){
if(!(valueToCheck.charCodeAt(i) >= 48 && valueToCheck.charCodeAt(i) <= 57)){
isValid = false;
break;
}
}
return isValid;
}
Here is the jsfiddle with tests cases.