I need a regular expression that validate for a number with length 4, 5, 6
I used ^[0-9]{4} to validate for a number of 4, but I do not know how to include validation for 5 and 6.
This question is related to
javascript
regex
Try this:
^[0-9]{4,6}$
{4,6}
= between 4 and 6 characters, inclusive.
Be aware that, as written, Peter's solution will "accept" 0000
. If you want to validate numbers between 1000
and 999999
, then that is another problem :-)
^[1-9][0-9]{3,5}$
for example will block inserting 0
at the beginning of the string.
If you want to accept 0 padding, but only up to a lengh of 6, so that 001000
is valid, then it becomes more complex. If we use look-ahead then we can write something like
^(?=[0-9]{4,6}$)0*[1-9][0-9]{3,}$
This first checks if the string is long 4-6 (?=[0-9]{4,6}$)
, then skips the 0s 0*
and search for a non-zero [1-9]
followed by at least 3 digits [0-9]{3,}
.
If the language you use accepts {}
, you can use [0-9]{4,6}
.
If not, you'll have to use [0-9][0-9][0-9][0-9][0-9]?[0-9]?
.
[0-9]{4,6}
can be shortened to \d{4,6}
Source: Stackoverflow.com