7

I have tried the following to only allow integers in my text box, this works great but it allows a zero in there. Is there anything else I can add to prevent a zero being added?

\d+
gideon
  • 19,329
  • 11
  • 72
  • 113
Funky
  • 12,890
  • 35
  • 106
  • 161

6 Answers6

7

This will allow 10 but not 01, and it will allow only numbers consisting of digits, i.e., no periods or minus signs...but also no plus signs, scientific notation etc.

^[1-9][0-9]*$
dnuttle
  • 3,810
  • 2
  • 19
  • 19
5

A minor variation is this:

/\d*[1-9]\d*/

That would allow leading zeros.

damog
  • 116
  • 1
  • 3
4

If you are not concerned about negatives and silly numbers like 07, this will do:

/[1-9]\d*/

For a more robust solution, I suggest converting the matched string to integer and check if it fulfills your criteria.

undur_gongor
  • 15,657
  • 5
  • 63
  • 75
  • a simple ^ anchor would deal with negatives – Alex K. Nov 15 '11 at 11:28
  • @Alex K: ... unless the number may appear in the mid of a string. To answer that (and similar problems), the question has to give much more details. – undur_gongor Nov 15 '11 at 11:30
  • 1
    @EduardoCuomo: Yes, it does ... as does the original regex in the question (`\d+`). I'm addressing only the "prevent a zero" part. Everything else is unclear in the question. – undur_gongor Mar 31 '15 at 08:26
2

Code:

^([1-9][0-9]+|[1-9])$

Example: http://regexr.com/3annd

Tested with:

0
10
01
11
00
1
100
Eduardo Cuomo
  • 17,828
  • 6
  • 117
  • 94
1
^(0*[1-9][0-9]*)$

This will allow "silly" numbers like 007 as well, but not 0 or 000 or an empty string.

Note that \d matches also digits from other character sets like ٠١٢٣٤٥٦٧٨٩. See: \d is less efficient than [0-9].

^ denotes the start, $ the end of the string. Together they ensure that the whole string is matched.

Community
  • 1
  • 1
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
0
^(\d{2}[1-9])$

matches with: from 001 to 999 example 001 099 999

does not match 000 01 0

Emis
  • 594
  • 1
  • 5
  • 11