7

This is a solution for validating an integer. Can someone please explain the logic of Karim's answer.
This works perfectly, but i am not able to understand how.

var intRegex = /^\d+$/;
if(intRegex.test(someNumber)) {
   alert('I am an int');
   ...
}
Community
  • 1
  • 1
Lalithesh
  • 164
  • 1
  • 2
  • 6
  • 1
    I think this question should better be a comment on that answer… and should be answered there by @Karim himself. – Bergi Jun 05 '13 at 13:55
  • 2
    Note that this code is not entirely correct. For example, it validates a string like `000...(10,000 times)..000` which is hardly a "number". – georg Jun 05 '13 at 13:58

4 Answers4

14

The regex: /^\d+$/

^ // beginning of the string
\d //  numeric char [0-9]
+ // 1 or more from the last
$ // ends of the string

when they are all combined:

From the beginning of the string to the end there are one or more numbers char[0-9] and number only.

gdoron
  • 147,333
  • 58
  • 291
  • 367
5

Check out a Regular Expression reference: http://www.javascriptkit.com/javatutors/redev2.shtml

/^\d+$/
^ : Start of string
\d : A number [0-9]
+ : 1 or more of the previous
$ : End of string
Louis Ricci
  • 20,804
  • 5
  • 48
  • 62
0

This regex may be better /^[1-9]+\d*$/

^     // beginning of the string
[1-9] // numeric char [1-9]
+     // 1 or more occurrence of the prior
\d    // numeric char [0-9]
*     // 0 or more occurrences of the prior
$     // end of the string

Will also test against non-negative integers that are pre-padded with zeroes

Jack
  • 419
  • 2
  • 5
0

What is a Nonnegative Whole Number?

A Nonnegative whole number is an "integer that is either 0 or positive."

Source: http://mathworld.wolfram.com/NonnegativeInteger.html

In other words, you are looking to validate a nonnegative integer.

The answers above are insufficient because they do not include integers such as -0 and -0000, which, technically, after parsing, become nonnegative integers. The other answers also do not validate integers with + in front.

You can use the following regex for validation:

/^(\+?\d+|-?0+)$/

Try it Online!

Explanation:

^                   # Beginning of String
    (               # Capturing Group
            \+?     # Optional '+' Sign
            \d+     # One or More Digits (0 - 9)
        |           # OR
            -?      # Optional '-' Sign
            0+      # One or More 0 Digits
    )               # End Capturing Group
$                   # End of String

The following test cases return true: -0, -0000, 0, 00000, +0, +0000, 1, 12345, +1, +1234. The following test cases return false: -12.3, 123.4, -1234, -1.

Note: This regex does not work for integer strings written in scientific notation.

Community
  • 1
  • 1
Grant Miller
  • 27,532
  • 16
  • 147
  • 165