Reputation: 11691
I am not very experienced with regex and I need to validate phone numbers using javascript.
I have a textbox which need to be allowed to accept multiple phone numbers with a delimiter of ';'
and the characters that can be allowed for the phone numbers are
Could someone help me on how I can acheive this using javascript and regex/ regular expressions?
Example:
+91-9743574891;+1-570-456-2233;+66-12324576
I tried the following:
^[0-9-+;]+$
Am not sure if this is correct.
Upvotes: 1
Views: 1170
Reputation: 92986
Your regex will match what you allow, but I would be a bit more restrictive:
^\+?[0-9-]+(?:;\+?[0-9-]+)*$
See it here on Regexr
That means match an optional "+" followed by a series of digits and dashes. Then there can be any amount of additional numbers starting with a semicolon, then the same pattern than for the first number.
Upvotes: 0
Reputation: 11182
You have placed -
in wrong place so, your regex
is not working.
Try this(your RegEx, but slightly modified):
^[0-9+;-]+$
or
^[-0-9+;]+$
To include a hyphen within a character class then you must do one of the following:
\-
,As the hyphen is used for specifying a range of characters. So, regex engine understands [0-9-+;]+
match any of the characters between 0
to 9
, 9
to +
(all characters having decimal code-point 57
[char 9
] to 43
[char +
] and it fails) and ;
.
Upvotes: 1
Reputation: 85785
How about this ^([0-9\-\+]{5,15};?)+$
Explanation:
^ #Match the start of the line
[0-9\-\+] #Allow any digit or a +/- (escaped)
{5,15} #Length restriction of between 5 and 15 (change as needed)
;? #An optional semicolon
+ #Pattern can be repeat once or more
$ #Until the end of the line
Only as restrictive as specified could be tighter, See it working here.
Upvotes: 0
Reputation: 48817
To be a bit more restrictive, you could use the following regexp:
/^\+[0-9]+(-[0-9]+)+(;\+[0-9]+(-[0-9]+)+)*$/
What it will match:
+91-9743574891
+1-570-456-2233;+66-12324576
What it won't match:
91-9743574891
+15704562233
6612324576
Upvotes: 0