4

Possible Duplicate:
A comprehensive regex for phone number validation

Whats the regex for

xxx-xxx-xxxx
or
(xxx)xxx-xxxx

I can create regex for the first one with

/^\d{3}-\d{3}-\d{4}$/

but how to add rule in this so it can also handle the second one?

Community
  • 1
  • 1
coure2011
  • 40,286
  • 83
  • 216
  • 349

3 Answers3

10

You can use this: -

/^(?:\(\d{3}\)|\d{3}-)\d{3}-\d{4}$/
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

I'm no guru but this should do the trick;

/^(\d{3}\-)?(\(\d{3}\))?\d{3}\-\d{4}$/
Daniel
  • 3,726
  • 4
  • 26
  • 49
  • Precisely, this will also match - `xxx-(xxx)xxx-xxxx`, but again it's not specified what OP don't want to match. So, it's a valid solution. – Rohit Jain Dec 03 '12 at 08:18
1
/^(\(\d{3}\))|(\d{3}-)\d{3}-\d{4}$/
atomAltera
  • 1,702
  • 2
  • 19
  • 38