-1

I have the following regex:

/[0-9\s-.]{8,10}/

It's purpose is for me to detect if user is entering anything that might be a phone number (Australian) into a description area and advise them to not do so. It works quite well to match numbers that may have spaces dots or hyphens in them.

Unfortunately it will also match stuff like "-----------". How can I make a digit required for a match and the other types optional?

Darren
  • 9,014
  • 2
  • 39
  • 50
  • 1
    can you list an example of the phone numbers that you're targeting? – Ibrahim Nov 18 '16 at 01:37
  • 2
    typing in "Javascript regex phone number" lists dozens of questions very similar to this one. Is there some reason those answers don't answer your question? – TemporalWolf Nov 18 '16 at 01:38

1 Answers1

0

You've almost got it. What you really want is this:

(?:\(\d\d?\)[\s-.])?\d{4}[\s-.]\d{4}

Demo on Regex101

To break it down a little:

  • (?:\(\d\d?\)[\s-.])? is the most intimidating-looking part, and really just describes an optional area code in brackets, followed by any one of a whitespace character, a dash, or a period.
  • \d{4} describes one of the two segments of the rest of the number.
  • [\s-.] is a character class, which (in this case) will match a whitespace character, dash, or period.
Sebastian Lenartowicz
  • 4,695
  • 4
  • 28
  • 39