Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
439 views
Welcome To Ask or Share your Answers For Others

1 Answer

An easier way would be to remove spaces and split the string first:

var emails = emailList.replace(/s/g,'').split(",");

This will create an array. You can then iterate over the array and check if the element is not empty and a valid emailadres.

var valid = true;
var regex = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;

for (var i = 0; i < emails.length; i++) {
     if( emails[i] == "" || ! regex.test(emails[i])){
         valid = false;
     }
}

note: I got the the regex from here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...