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.