1

I'm trying to validate the phone number value, I have this regEx /^\d+(-\d+)*$/ allowing a number with dashes in between of numbers. I find it here, but I forgot the link. And I try to edit it to optionally allowed parentheses, dots, dashes, spaces, and plus sign but I'm a beginner so that for now I can't do this to work. And please note that the user is free what format they are like to use, it simply allow them to input either dashes, space, plus sign, dots, and parentheses.

Value allowed:

  • 0123456789
  • 012-345-6789
  • 012-345-6789
  • (012)-345-6789
  • (012) 345-6789
  • +0123456789
  • +012-345-6789
  • +(012)-345-6789

Someone please help me.

jho1086
  • 1,998
  • 2
  • 16
  • 25
  • 1
    possible duplicate of [A comprehensive regex for phone number validation](http://stackoverflow.com/questions/123559/a-comprehensive-regex-for-phone-number-validation) – Andy Lester Dec 03 '12 at 05:51
  • oh, please pardon me I try many times searching this, but the link you gave didn't appear. – jho1086 Dec 03 '12 at 09:45
  • What language are you using? I bet there's already a package or module that already does this. Problems like this are well solved. People have been writing code to validate phone numbers for years and years, and the code to do it exists and is well-tested. – Andy Lester Dec 03 '12 at 15:41

2 Answers2

0

To validate those phone number patterns, you may be able to use this:

/\v^\+?\(?(\d{3})\)?\s?[-.]?\(?(\d{3})\)?[-.]?\(?(\d{4})\)?$/

The only downside is that it doesn't match phone numbers with extensions, should you care about those.

"Value allowed" phone validation matches highlighted in Vim

JSON
  • 35
  • 8
-1
[0-9\-\(\)\+\s]+

You can use that to check and/or use a regex replace to remove all those characters and validate the result.

For replacement, you might want: [^0-9]

Matthew Scragg
  • 4,540
  • 3
  • 19
  • 27
  • 1
    Your regex needs anchors, otherwise it will match as soon as there is one character out of the character class in the input string, e.g. stuff like "Foo(((((bar". The other thing I don't like is, the OP has obviously no idea about regex and your answer does not explain anything. – stema Dec 03 '12 at 07:29