Reputation: 509
I want to validate a United States phone number, this is what I have so far:
var numberRegex = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/
My problem with this is that this allows single bracket.
This will allow to pass an opening parenthesis without a closing one like this: (111-121-1212
.
Does anyone have a regex script that will match a U.S phone number and account for brackets?
Upvotes: 0
Views: 1592
Reputation: 57719
I would advise against this. The only way to validate a phone number is too try and call it and see who picks up. A phone number may look syntactically correct, but it can still be semantically wrong (ie. a fake phone number).
The best you can do is give the user a warning that the phone-number "doesn't look valid" but accept any input anyway.
Upvotes: -1
Reputation: 64563
Use alternatives (|
):
(?:
\(([0-9]{3})\)
|
([0-9]{3})
)
Resulting re looks like:
var numberRegex = /^(?:\(([0-9]{3})\)|([0-9]{3}))[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/
Upvotes: 2