Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
444 views
in Technique[技术] by (71.8m points)

javascript - 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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...