Validate a comma separated email list

前端 未结 5 980
北恋
北恋 2021-01-04 11:00

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

5条回答
  •  走了就别回头了
    2021-01-04 11:24

    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

提交回复
热议问题