How to match a comma separated list of emails with regex?

前端 未结 13 1211
一整个雨季
一整个雨季 2020-12-15 07:29

Trying to validate a comma-separated email list in the textbox with asp:RegularExpressionValidator, see below:



        
相关标签:
13条回答
  • 2020-12-15 08:00

    A simple modification of @Donut's answer allows adjacent commas, all TLDs of two characters or more, and arbitrary whitespace between email addresses and commas.

    ^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,}(\s*,?\s*)*)+$
    

    You will need to split and remove whitespace and empty strings on your side, but this should be an overall better user experience.

    Examples of matched lists:

    • person@example.co,chris@o.com,simon@example.capetown
    • person@example.co ,, chris@o.com, simon@example.capetown
    0 讨论(0)
  • 2020-12-15 08:01

    This Regex will allow emails with spaces after the commas.

    ^[\W]*([\w+\-.%]+@[\w\-.]+\.[A-Za-z]{2,4}[\W]*,{1}[\W]*)*([\w+\-.%]+@[\w\-.]+\.[A-Za-z]{2,4})[\W]*$
    

    Playing around with this, a colleague came up with this RegEx that's more accurate. The above answer seems to let through an email address list where the first element is not an email address. Here's the update which also allows spaces after the commas.

    0 讨论(0)
  • 2020-12-15 08:03

    The first answer which is selected as best matches the string like abc@xyz.comxyz@abc.com which is invalid.

    The following regex will work for comma separated email ids awesomely.

    ^([\w+-.%]+@[\w.-]+\.[A-Za-z]{2,4})(,[\w+-.%]+@[\w.-]+\.[A-Za-z]{2,4})*$
    

    It will match single emailId, comma separated emailId but not if comma is missed.

    First group will match string of single emailId. Second group is optionally required by '*' token i.e. either 0 or more number of such group but ',' is required to be at the beginning of such emailId which makes comma separated emailId to match to the above regex.

    0 讨论(0)
  • 2020-12-15 08:04

    The solution that work for me is the following

    ^([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)(,([a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+))*
    
    0 讨论(0)
  • 2020-12-15 08:06

    The regex below is less restrictive and more appropriate for validating a manually-entered list of comma-separated email addresses. It allows for adjacent commas.

    ^([\w+-.%]+@[\w-.]+\.[A-Za-z]{2,4},*[\W]*)+$
    
    0 讨论(0)
  • 2020-12-15 08:08

    Use the following regex, it will resolve your problem. The following regex will entertain post and pre spaces with comma too

    /^((([a-zA-Z0-9_-.]+)@([a-zA-Z0-9_-.]+).([a-zA-Z\s?]{2,5}){1,25})(\s?,\s*?))$/
    
    0 讨论(0)
提交回复
热议问题