Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 801
Frank B Avatar asked Jun 07 '12 16:06

Frank B


People also ask

What is non digit regex?

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).

How do you validate expressions in regex?

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.

How do I check if a number is only in regular expressions?

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.

Can you write a regular expression to check if string is a number?

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].


2 Answers

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.

like image 54
gdoron is supporting Monica Avatar answered Nov 14 '22 23:11

gdoron is supporting Monica


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.

like image 37
ZER0 Avatar answered Nov 15 '22 01:11

ZER0