简体   繁体   中英

Validating comma separated emails in c# with regex

I am trying to validate a string of comma separated emails in c#

So far this has worked:

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

But I need it to not allow the emails if they are separated by multiple commas. For example:

test@test.com,,test@test.com

would send back an invalid email and let the user know to retype it in.

I would suggest splitting the string before you do the regex. you can check for empty strings to see if they had two commas in there back-to-back.

Then you're just left with the normal problem of the email address regex, which, as you can see:

https://stackoverflow.com/search?q=Email+address+validation

has been asked about a bajillion times and there's not really one good answer.

The language I've used is VB.NET, but the methods remain the same:

Imports System.Net.Mail

Module Module1

    Friend Function IsValidEmailAddress(a As String) As Boolean
        Dim isValid As Boolean = False
        Try
            Dim e = New MailAddress(a)
            isValid = True
        Catch ex As FormatException
            isValid = False
        End Try

        Return isValid

    End Function

    Sub Main()
        Dim addressesToCheck = "test@test.com,,test@test.com,notanemailaddress"
        Dim addresses = addressesToCheck.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries)
        For Each a In addresses
            Console.WriteLine(String.Format("{0} valid: {1}", a, IsValidEmailAddress(a)))
        Next

        Console.ReadLine()

    End Sub

End Module

Outputs:

test@test.com valid: True
test@test.com valid: True
notanemailaddress valid: False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM