Internet Engineer
Internet Engineer

Reputation: 2534

regex phone with mask

I am trying to get a regex that will allow me to validate a phone with a mask.

The mask is () -

Example (333) 444-5555

Rules:

  1. No preceding or trailing spaces
  2. No spaces inside the parenthesis
  3. 3 digits are expected inside the parenthesis
  4. 1 space is expected after the closing parenthesis
  5. Then 3 digits + a dash and then the remaining 4 digits

So far this is what I have but it allows phones without parenthesis:

^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$

Upvotes: 0

Views: 134

Answers (2)

Braj
Braj

Reputation: 46871

As per rule it should work

^\(\d{3}\) \d{3}-\d{4}$

You can use [0-9] instead of \d as well.

? means zero and one time

Upvotes: 1

xenomancer
xenomancer

Reputation: 46

Here's my take on it:

^((\(\d{3}\)|\d{3})(\s|-|\.))?\d{3}(\s|-|\.)?\d{4}$

Upvotes: 0

Related Questions