1

I have created a regex for validating a telephone number with following requirement:

  • Allowed chars: + space ( ) – 0-9

  • + or ( can be first char after trim like (+61) 312 405 678 or +61 312 405 678.

  • Dash is allowed anywhere in the number.

  • Length min 8 max 16 – show error in case of boundary conditions

But I need to enhance it a bit. I want to validate that if + is in the number it must be only in the beginning but my regex is not checking this. Please help. This is my regex so far:

^[\\(?\\+?(\\d{2})\\)?[- ]?(\\d{0,})[- ]?(\\d{0,})[- ]?(\\d{0,})]{9,16}$
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – Brian Roach Sep 03 '11 at 16:27
  • @brian-roach: i checked all the regex supplied their they all have the same issue i just mentioned about open and close bracket. – Hardik Handa Sep 03 '11 at 19:12

2 Answers2

1

Adding \+{0,1} to the beginning should do the trick.

The finished regex would look like this

^\+{0,1}[\(?\+?(\d{2})\)?[ -]?(\d{0,})[- ]?(\d{0,})[- ]?(\d{0,})]{9,16}$

D_V
  • 416
  • 3
  • 16
  • That's close, but the `+` can be inside the first `()` or outside. I just noticed his whole regex is a group, which I don't think is what he needs. – Brian Roach Sep 03 '11 at 16:25
  • @brian-roach : yes that's what i need enhancement to what i have already created !! – Hardik Handa Sep 03 '11 at 18:35
  • also i just checked with some more test cases and the above regex failed : +61) 456 789 980 it should have stated false for the above input as we dont have an open bracket but it is giving true for the same ! – Hardik Handa Sep 03 '11 at 18:45
  • Found solution, thought it might help someone else in future: ^[[\\+?[\\d]{2}]?[\\s \\-]?[\\d [\\- \\s]?]]{9,15}$|[\({1}]\\+{1}\\d{2}[\){1}][[\\s \\-]?[\\d [\\- \\s]?]]{9,10}$ Did this myself atlast ;) – Hardik Handa Sep 04 '11 at 18:42
  • Doesn't Java support `\+?` instead of `\+{0,1}`? – tripleee Sep 05 '11 at 10:14
0

I would throw out all the optional characters, then check if it matches \\+?\\d{8,16}.

Alternatively, allow for arbitrary amounts of punctuation anywhere; [\\s().-]*(\\+[\\s().-]*)?(\\d[\\s().-]*){8,16}.

tripleee
  • 175,061
  • 34
  • 275
  • 318
  • Found solution, thought it might help someone else in future: ^[[\\+?[\\d]{2}]?[\\s \\-]?[\\d [\\- \\s]?]]{9,15}$|[\\({1}]\\+{1}\\d{2}[\\){1}][[\\s \\-]?[\\d [\\- \\s]?]]{9,10}$ Did this myself atlast ;) – Hardik Handa Sep 04 '11 at 18:41
  • Your regex looks mighty strange, and will fail if there are multiple consecutive spaces. – tripleee Sep 05 '11 at 10:14
  • could u suggest any improvement ?? – Hardik Handa Sep 05 '11 at 17:30
  • Reluctantly edited my response. It would help if we knew in what context and for what purpose you need this. – tripleee Sep 06 '11 at 05:45