Reputation: 6820
I need a Regex for validating a phone number. White space allowed (but only one at a time).
OK: +45 1234 1234
NOT OK: +45 1234 1234
OK: 0045 54 45 45 45
NOT OK: 0045 54 45 45 45
I tried /^[+]?[0-9\s-]*$/
but it's not working as it allows for multiple white space.
Upvotes: 1
Views: 434
Reputation: 627380
Your ^[+]?[0-9\s-]*$
regex matches a string that starts with an optional plus ([+]?
) and then has an unlimited amount (0 or more) of digits, whitespaces or hyphens, thus, it even matches "+ --- "
string:
You need to use
/^\+?[0-9]+(?:[\s-][0-9]+)*$/
See the regex demo and the regulex graph:
Mind to keep -
at the end of the character class in [\s-]
if you want to keep it unescaped, or escape the hyphen inside the character class, [\s\-]
.
Details
^
- start of a string\+?
- an optional +
symbol[0-9]+
- one or more digits(?:[\s-][0-9]+)*
- a non-capturing group that matches 0 or more repetitions of
[\s-]
- a character class matching a single whitespace or -
[0-9]+
- 1 or more digits$
- end of stringUpvotes: 1
Reputation: 44145
Try using this regex:
var re = /^\+?\d+(\s\d+)*$/;
var strings = ["+45 1234 1234", "+45 1234 1234", "0045 54 45 45 45", "0045 54 45 45 45"];
strings.forEach(s => console.log(s.match(re)));
Upvotes: 1