How do I form a regex to validate a range from 1 to 1000, where the number 001 is same as 1, 0245 is same as 245. Most solutions I saw allowed the range check but did not allow the number to start with 0. The problem is with not allowing 0,00,000, but allow the number to start with or without 0.
Edit: it should allow 1,01,001 and not any number exceeding 4 digits.
There are a couple ways you can do this. My first thought is something like this:
/^0*(1000|[1-9]\d{0,2})$/
Explanation:
The 0*
consumes any leading zeroes. After that, you're looking for either 1000 or a 1- to 3-digit number that doesn't start with zero. The [1-9]
requires that at least one nonzero digit is present, and the \d{0,2}
allows up to two digits after that (so numbers ending in zero are still allowed).
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