Validate a comma separated email list

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

    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,]+)$

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-04 11:26

    const regExp = new RegExp(/^(\s?[^\s,]+@[^\s,]+\.[^\s,]+\s?,)*(\s?[^\s,]+@[^\s,]+\.[^\s,]+)$/);
    const dom = document.getElementById("regExDom");
    const result = regExp.test("test@gmail.com,test2@gmail.com,test3@test.com")
    console.log("Regex test => ", result)
    dom.innerHTML = result;
    <div id="regExDom"></div>

    0 讨论(0)
  • 2021-01-04 11:35

    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 :)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题