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!
The uppercase counterpart \D (non-digit) matches any single character that is not a digit (same as [^0-9] ). \s (space) matches any single whitespace (same as [ \t\n\r\f] , blank, tab, newline, carriage-return and form-feed).
When you create a text question, along with word/character limits, you can validate for Regex pattern matching. To validate a field with a Regex pattern, click the Must match pattern check box.
If you want to get only digits using REGEXP, use the following regular expression( ^[0-9]*$) in where clause. Case 1 − If you want only those rows which have exactly 10 digits and all must be only digit, use the below regular expression.
Same regular expression for checking String for numbers can also be written without using predefined character set and using character class and negation as shown in following example : Pattern pattern = Pattern. compile(". *[^0-9].
Simply:
function validInteger(theNumber){
return theNumber.match(/^\d+$/) && parseInt(theNumber) > 0;
}
Live DEMO
Or even simpler with regex
only as suggested by @Eric:
return /^[0-9]\d*$/.test(theNumber);
Live DEMO
Update:
An excellent cheat sheet. The link died after 5 years, sorry.
If it's okay don't use RegExp, you can have:
function validInteger(theNumber){
var number = +theNumber;
return number > -1 && number % 1 === 0;
}
Assuming that you consider 0 as positive integer, and you don't want to make a distinction between +0 and -0.
Notice that this function will accept any value for theNumber
that can be converted in a Number, so not just "string", and you can pass Number as well of course.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With