Using a regular expression to check if an input has any digits in it

function validInteger(theNumber){
    var anyNonDigits = new  RegExp('\D','g');
    if(parseInt(theNumber)&&!anyNonDigits.test(theNumber)){
        return true;
    }else{
        return false;
    }
}

Above was the function that I wrote to confirm the input. I want all positive integers. The problem I encountered is related to the RegExp object. It seems to be super simple, but for some reason it doesn't work.

For example, if I pass 'f5', I get true, but if I pass '5f', I get false. I am also having problems passing negative numbers. -3 doesn't hit even if I build the variable before passing it to RegExp. I can fix this by adding ' &&parseInt(theNumber)>0' to my if statement, but I feel that RegExp should catch it too. Thanks in advance!

+5
3

:

function validInteger(theNumber){    
    return theNumber.match(/^\d+$/) && parseInt(theNumber) > 0;
}

Live DEMO

regex @Eric:

return /^[0-9]\d*$/.test(theNumber);

Live DEMO

Update:

-.

+11

, RegExp, :

function validInteger(theNumber){
    var number = +theNumber;

    return number > -1 && number % 1 === 0;
}

, 0 , +0 -0.

, theNumber, , "", .

+1

!

function validate(num){
    return (num | 0) > 0;
};

"" .

0

All Articles