Reputation: 1492
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
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}$/
/
: Delimiters of regex literal^
: Starts with anchor\+\d{1,3}
: One to three digits after +
\d
: Matches single digit\(
: Matches (
literally\d{2}
: Matches exactly two digits\)
: Matches )
literally-
: Matches -
literally\d{6}
: Matches exactly six digits$
: Ends with anchorLive Demo
input:valid {
color: green;
}
input:invalid {
color: red;
}
<input type="text" pattern="(\+\d{1,4})?\(\d{2}\)-\d{6}" />
Upvotes: 1
Reputation: 1212
^\D*(?:\d\D*){10,}$
^^
[+()-]
just point out your regex problem
\D
: any characters except digits
Upvotes: 3