AngelicCore
AngelicCore

Reputation: 1453

Regex for list of emails, validating invalid email addresses

I have the following regex for validation a list of Email addresses seperated by a ';'

\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*([;]\s*\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*

It used to work correctly (for my tests) until I discovered a problem with it.

It not only allows stuff like this (intended) [email protected];[email protected];[email protected]

It allows stuff like this: (not intended) [email protected]@[email protected]

Where is the problem with it?

Upvotes: 2

Views: 3189

Answers (3)

rvalvik
rvalvik

Reputation: 1559

Validating emails one at the time is probably your most clean bet, otherwise the regex can get pretty ugly. Especially if you later add more complex requirements to the addresses. A big benefit of doing a single address at the time is that you have a well tried problem, namely how to validate an email address using regex.

Upvotes: 1

user21033168
user21033168

Reputation: 444

This is the standard way to check emails with regex: \b\w+@[\w.]+\.[A-z.]{2,4}\b
It's not perfect, but it should work for your example.
You could also split the string by semicolons, and then validate the emails one by one.

Upvotes: 1

Petr Behenský
Petr Behenský

Reputation: 620

Try this one:

(?:(?:^|;)\w+(?:[-+.]\w+)*@\w+(?:[-.]\w+)*\.\w+(?:[-.]\w+)*)+$

Upvotes: 0

Related Questions