Reputation: 43
I am trying to do a regular expression to validate a number between 9 and 13 numbers, but the sequence can have dashes and spaces and the ideal is to not have more than one space or dash consecutively.
this rule allow me to control the validation between 9 and 13
/^[\d]{9,13}$/
now to add dashes and spaces
/^[\d -]{9,13}$/
I think I need something like that, but I need to count the numbers
/^[ -](?:\d){9,13}$/
Any tips?
Upvotes: 3
Views: 6944
Reputation: 70732
It appears that you don't want leading or trailing spaces and dashes. This should do it.
/^\d([- ]*\d){8,12}$/
Regular expression:
\d digits (0-9)
( group and capture to \1 (between 8 and 12 times)
[- ]* any character of: '-', ' ' (0 or more times)
\d digits (0-9)
){8,12} end of \1
Another option: A digit followed any number of space or dash 8-12 times, followed by a digit.
/^(\d[- ]*){8,12}\d$/
Upvotes: 3
Reputation: 55619
Assuming a dash following a space or vice versa is ok:
^( -?|- ?)?(\d( -?|- ?)?){9,13}$
Explanation:
( -?|- ?)
- this is equivalent to ( | -|-|- )
. Note that there can't be 2 consecutive dashes or spaces here, and this can only appear at the start or directly after a digit, so this prevents 2 consecutive dashes or spaces in the string.
And there clearly must be exactly one digit in (\d( -?|- ?)?)
, thus the {9,13}
enforces 9-13 digits.
Assuming a dash following a space or vice versa is NOT ok:
^[ -]?(\d[ -]?){9,13}$
Explanation similar to the above.
Both of the above allows the string to start or end with a digit, dash or space.
Upvotes: 0
Reputation: 425208
Use look aheads to assert the various constraints:
/^(?!.*( |--))(?=(\D*\d){9,13}\D*$)[\d -]+$/
Upvotes: 0
Reputation: 18155
Notice how my regex starts and ends with a digit. Also, this prevents consecutive spaces and dashes.
/^\d([ \-]?\d){7,12}$/
Upvotes: 4