Validate a comma separated email list

前端 未结 5 1096
北恋
北恋 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:39

    Also note that you'll want to get rid of extra spaces so an extra step needs to be added as follows:

    var emailStr = "felipe@google.com   , felipe2@google.com, emanuel@google.com\n";
    
    
    function validateEmailList(raw){
        var emails = raw.split(',')
    
    
        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].replace(/\s/g, ""))){
                valid = false;
            }
        }
        return valid;
    }
    
    
    console.log(validateEmailList(emailStr))
    

    By adding .replace(/\s/g, "") you make sure all spaces including new lines and tabs are removed. the outcome of the sample is true as we are getting rid of all spaces.

提交回复
热议问题