1

I was browsing through the internet to find a proper javascript regular expression for phone numbers but the ones I find are not the ones I need.

The acceptable phone number type for my case would have to match the following rules:

  • May start with + or 0-9
  • all rest string is allowed to have only 0-9, - and space (preferably only 1 space between numbers)

I tried so far this: /^\+[\-\d\s]/ but I am not getting the proper result. I've tried to read some tutorials but I am very new to this and it seems I am missing something.

An acceptable phone number for example would be: +30 6995 4488551 (spaces allowed) or 0030 6995 4488551 etc.

Any help would be much appreciated! :)

Dimitris Damilos
  • 2,363
  • 5
  • 23
  • 46
  • Dashs, spaces, hyphens, etc are formatting. Don't allow or reject them - ignore them when you test. – Quentin Feb 14 '13 at 17:18
  • Maybe this is what you're looking for? [link]http://stackoverflow.com/questions/4147614/javascript-regular-expression-for-international-phone-number[/link] – itsid Feb 14 '13 at 17:18
  • Thank you for the replies but those answers of that topic are not what I need, because in the answers they just strip the characters they don't want and validate the rest. I don't think that's a good way of dealing with it. I want for the user to input correct strings. For example, the users cannot input `+` wherever they want, but only at the beginning. – Dimitris Damilos Feb 14 '13 at 17:28

2 Answers2

1

Your regex matches anything that starts with a + followed by a single -, digit or whitespace character. So you will match for example:

  • +4qwertzuiopasdfghjkl
  • +-asdfasdfasdfasdf

I suggest you to look at the examples and tutorials on http://www.regular-expressions.info/. As for your telephone numbers a better regex would be:

/^\+?[\d -]+$/

This would match all valid numbers but also invalid constructions like +--------- or simply + with a trailing space. If you want to be really close to denying a lot of invalid combinations I would suggest you read this, but as you can see the regexes get messy.

Community
  • 1
  • 1
crackmigg
  • 5,571
  • 2
  • 30
  • 40
1

Adding to migg's answer -- you could add more filters after the regex test that could, for example, make sure there are at least a minimum number of digits in the expression, or what have you. e.g.,

 if !(phone_number.match(/\d/g).length == 9) inValidate()