简体   繁体   中英

Using a regular expression to validate whether input has any non digits in it

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!

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.

Be simple!

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

This function will return "true" only for positive integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM