I have an application that needs to handle validation for phone numbers. Phone numbers are required to have 13 characters (sum of numbers and dashes). There must be at least 1 dash and a maximum of 3 dashes. The starting character must be a digit. How can I create a regex for this validation? Here is my regex string. /^(?:[0-9]-*){13}$/
It doesn't work exactly what I expected
CodePudding user response:
You can use
^(?=.{13}$)[0-9] (?:-[0-9] ){1,3}$
^(?=.{13}$)\d (?:-\d ){1,3}$
See the regex demo. Details:
^
- start of string(?=.{13}$)
- the string must contain exactly 13 chars[0-9]
/\d
- one or more digits(?:-[0-9] ){1,3}
/(?:-\d ){1,3}
- one, two or three repetitions of a hyphen followed with one or more digits$
- end of string.
CodePudding user response:
So 13 characters in total with a maximum of 3 dashes and a minimum of 1 means 10 digits right? Therefor your characters are ranging 11-13?
If so, try:
^(?=(?:\d-?){10}$)\d (?:-\d ){1,3}
See an online demo
^
- Start line anchor.(?=
- Open a positive lookahead:(?:
- Open a non-capture group:\d-?
- Match a digit and optional hyphen.){10}$)
- Close the non-capture group and match it ten times before the end-string anchor. Then close the lookahead.
\d
- 1 Digits.(?:
- Open a 2nd non-capture group:-\d
- Match an hyphen and 1 digits.){1,3}
- Close non-capture group and match it 1-3 times.