theITvideos
theITvideos

Reputation: 1492

Regular Expression for a phone number excluding special characters

I'm using a regular expression for a phone number. It allows at least 10 digits including special characters like +()-

+1(33)-489256

The Regular expression I am using is:

^\D*(?:\d\D*){10,}$

It works OK but it should not allow other special characters in the phone number like #@$%

Please let me know how I can update my regex.

Upvotes: 2

Views: 7769

Answers (2)

Tushar
Tushar

Reputation: 87203

The problem in your regex is \D*, this will match any non-digit characters(including special characters) any number of times.

Use

/^(\+\d{1,4})?(\d{2}\)-\d{6}$/

Regex Demo and Explanation

  1. /: Delimiters of regex literal
  2. ^: Starts with anchor
  3. \+\d{1,3}: One to three digits after +
  4. \d: Matches single digit
  5. \(: Matches ( literally
  6. \d{2}: Matches exactly two digits
  7. \): Matches ) literally
  8. -: Matches - literally
  9. \d{6}: Matches exactly six digits
  10. $: Ends with anchor

Live Demo

input:valid {
  color: green;
}
input:invalid {
  color: red;
}
<input type="text" pattern="(\+\d{1,4})?\(\d{2}\)-\d{6}" />

Upvotes: 1

Kerwin
Kerwin

Reputation: 1212

^\D*(?:\d\D*){10,}$
         ^^
       [+()-]

just point out your regex problem

\D: any characters except digits

Upvotes: 3

Related Questions