1

I'm implementing a validator function in a form that has this regex /^[\d\s ().-]+$/ for phone numbers.

I would like to change it to accept a starting + and then all combinations of [0-9] . - , ( ).

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Rikard
  • 7,485
  • 11
  • 55
  • 92

4 Answers4

5

since you want to start with +, you need to tell the engine to start with + by escaping it since it has another meaning,

/^\+[\d\s ().-]+$/

the answer simply answers what you ask but the it does not give you proper result since it will match with +...,..(), I can modify this if you can specifically tell us the acceptable patter you want, eg +639151234567

John Woo
  • 258,903
  • 69
  • 498
  • 492
4

That's pretty easy. Don't forget to escape the "+". I assume the "+" is optional, thus use the ? quantifier.

/^\+?[0-9(),.-]+$/
Pik'
  • 6,819
  • 1
  • 28
  • 24
  • `\+?` makes `+` optional. – John Woo Aug 04 '13 at 19:53
  • 1
    I know and said it in the answer. – Pik' Aug 04 '13 at 19:56
  • 1
    @491243: The problem relies in our definition of "accept". It can mean you *expect* a starting "+", or *allow* the user to start the string by a "+". Either way, it's no big deal, the OP will choose to add the `?` or not. – Pik' Aug 04 '13 at 20:01
0

Below regex can match any type of number, remember, I have assumed + to be optional. However it does not handle number counting

^\+?(\d[\d-. ]+)?(\([\d-. ]+\))?[\d-. ]+\d$

Here are some valid numbers you can match:

+91293227214
+3 313 205 55100
99565433
011 (103) 132-5221
+1203.458.9102
+134-56287959
(211)123-4567
111-123-4567
softvar
  • 17,917
  • 12
  • 55
  • 76
  • 2
    You're adding rules the original regex didn't have (e.g regarding parenthesis), so you need to explain them in your answer. – Pik' Aug 04 '13 at 20:05
  • being a simple regex, what to explain, hah ! i didn't do any extraordinary thing, it's just what the user wants :) – softvar Aug 05 '13 at 11:45
  • Indeed, it's a simple regex... Except when you're still learning regexes. :) Explaining the regex will be at least useful for the OP. – Pik' Aug 05 '13 at 16:23
0

Well, this is the best I can come up with. I merged many of the regex given in other answers.

/^[+]?(1\-|1\s|1|\d{3}\-|\d{3}\s|\d{2}\-|\d{2}\s|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3}) 
(\-|\s)?(\d{4})$/g

This should support all combinations like

  1. (541) 754-3010
  2. +1-541-754-3010
  3. 1-541-754-3010
  4. 001-541-754-3010
  5. 191 541 754 3010
  6. +91 541 754 3010

and so on.

  • Please don't post multpile times the same answer: https://stackoverflow.com/a/59734390/372239 https://stackoverflow.com/a/59735221/372239 https://stackoverflow.com/a/59735305/372239 – Toto Jan 14 '20 at 14:09