Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate a comma separated email list

I'm trying to come up with a regular expression to validate a comma separated email list.

I would like to validate the complete list in the first place, then split(";"), then trim each array value (each email) from the split.

I would like to validate the following expressions:

EMAIL,EMAIL  --> Ok
EMAIL, EMAIL  --> Ok
EMAIL , EMAIL  --> Ok
EMAIL , , EMAIL  --> Wrong
EMAIL , notAnEmail , EMAIL  --> Wrong

I know there's many complex expressions for validating emails but I don't need anything fancy, this just works for me: /\S+@\S+\.\S+/;

I would like plain and simple JS, not jQuery. Thanks.

Edit: I've already considered fist validate then split, but with the expressions I've tried so far, this will be validated as two correct emails:

EMAIL, EMAIL  .  EMAIL

I would like to validate the list itself as much as every email.

like image 851
user2256799 Avatar asked May 21 '14 07:05

user2256799


2 Answers

I am using the Regex from many years and code is same. I believe this works for every one:

^(\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]{2,4}\s*?,?\s*?)+$

Be happy :)

like image 147
Sunny_Sid Avatar answered Oct 05 '22 04:10

Sunny_Sid


I agree with @crisbeto's comment but if you are sure that this is how you want to do it, you can do it by matching the following regex:

^(\s?[^\s,]+@[^\s,]+\.[^\s,]+\s?,)*(\s?[^\s,]+@[^\s,]+\.[^\s,]+)$

like image 37
sshashank124 Avatar answered Oct 05 '22 03:10

sshashank124