0

I want to validate an text input field with javascript regex validation.
Validation that is needed is: Input field should have one or multiple email ids, all ending with semicolon(;).

Thus, correct input would be :
→ user1@xxx.com;
→ user1@xxx.com;user2@xxx.com;
→ user1@xxx.com;user2@xxx.com;user3@xxx.com;

Incorrect input would be
→ user1@xxx.com                            -------- Semicolon is missing
→ user1@xxx                                    -------- Email Id is invalid
→ user1@xxx.com;user2@xxx.com -------- Semicolon(;) is missing after second email id


This is what I have tried so far which validates only one occurence of regex pattern, but not all occurences in single line.

(^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(;)+$)


Regex URL: https://regex101.com/r/4svUQz/2/
[All 4 values in TEST STRING should match, but it is matching only first 2]

Also, I have checked below articles, but could not find answer.
Regex single-line multiple match
Regex for The Same Pattern Multiple Times in One Line
How to validate an email address in JavaScript

Toto
  • 89,455
  • 62
  • 89
  • 125
foodiepanda
  • 128
  • 1
  • 14

1 Answers1

1

First, for a simpler email regex to understand the principles involved, see How to check for a valid email address?. I will use: [^@]+@[^@]+\.[^@]+ with the recommendation that we also exclude space characters and so, in your particular case requiring a semicolon at the end and allowing multiple email addresses on the line:

^([^@\s]+@[^@\s]+\.[^@\s.]+;)+$

Note that I took the basic regex for an email address and appended ; and then put parentheses () around the entire expression and appended + signifying one or more times.

See Regex Demo

Using your regex, with a slight simplification involving the ; (i.e. removing unnecessary parentheses surrounding it):

^([a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+;)+$

See Regex Demo

Booboo
  • 38,656
  • 3
  • 37
  • 60