I trying to validate 5 comma separated email id in one regular expression. I currntly using below regex
^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},?)+$
This is valid for one email id.
I would like to know how I can achieve the same, any small inputs on the same is also greatly appreciated.
Thanks in advance.
Below regex for javaScript you can use for multiple comma separated email id, hope this work for you
First of all, fix the pattern:
-
in between two chars inside a character class forms a range. So, the email part of your regex should be[-\w+.%]+@[\w-.]+\.[A-Za-z]{2,4}
(note the position of-
in the first character class, in the second, it is OK to put it between a shorthand character class\w
and the next char).Next, to match 1 to 5 comma-separated emails, you need to match the first one, and then match 0 to 4 emails. And add anchors around the pattern to make sure the pattern matches the whole string:
Basically,
^<EMAIL>(?:,<EMAIL>){0,4}$
:^
- start of string<EMAIL>
- an email pattern of yours(?:
- start of a non-capturing group acting as a container for a sequence of patterns:,
- a comma<EMAIL>
- an email pattern of yours){0,4}
- zero to four occurrences of these sequences above$
- end of string.Another idea is to split with
,
and then validate: