I currently use "(\d){1,9}", but it fails to invalidate numbers such as "0134". The expression must only validate numbers that are positive INTEGERS. Thanks.
Right now you use the expression [0-9]{1,9}
, so this clearly allows the number 0134
. When you want to require that the first character is not a zero, you have to use [1-9][0-9]{0,8}
.
By the way: 0134 is a positive integer. It is an integer number, and it is positive. ;)
edit:
To prevent integer overflow you can use this pattern:
[1-9][0-9]{0,8}
[1-1][0-9]{9}
[2-2][0-1][0-9]{8}
[2-2][1-1][0-3][0-9]{7}
[2-2][1-1][4-4][0-6][0-9]{6}
I think you get the idea. Then you combine these expressions with |
, and you are done.
Alternatively, have a look at the Integer.valueOf(String)
method, how it parses numbers and checks for overflow. Copy that code and change the part with the NumberFormatException
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With