function validInteger(theNumber){
var anyNonDigits = new RegExp('\D','g');
if(parseInt(theNumber)&&!anyNonDigits.test(theNumber)){
return true;
}else{
return false;
}
}
Above is a function I've written to validate some input. I want all positive integers. The problem I'm facing is with the RegExp object. This seems like it should be super simple, but for some reason it's not working.
For example if I pass 'f5' I get true, but if I pass '5f' I get false. I'm also having problems when passing negative numbers. -3 doesn't get caught even if I stringify the variable before passing it into the RegExp. I can fix this by adding '&&parseInt(theNumber)>0
' in my if statement, but I feel like the RegExp should catch that too. Thanks in advance!
\
character since\
also has meaning in string literal notation.new RegExp('\\D','g');
– Roarkg
modifier, since it sounds as though even one non-digit should be enough to flag the input. – Roark