Bergi is correct that the way you build a regular expression is incorrect.
Another problem is that you are missing the anchors and + :
var re = /^[\d\s()+-]+$/;
Please note that the regex-based solution will still allow some inputs that are not valid phone numbers. You can improve your regular expression in many ways, for example, you can require that, for example, there are at least x digits.
There are many rules for which phone numbers are valid and invalid. It is unlikely that you could encode all of these rules in regular expression in a supported way so that you could try one of these approaches:
- Find a library capable of checking phone numbers (but maybe not based on regular expressions).
- If you need a regular expression, use a goal close to the rules, but don't try to handle all special cases. I would suggest trying to write an expression that accepts all valid phone numbers, but does not necessarily reject all invalid phone numbers.
You may also consider writing test cases for your solution. Tests will also be doubled as a form of documentation, which inputs you want to accept and reject.
source share