Search code examples
asp.netvb.nettextboxemail-validation

ASP Email Validator


I have a textbox with multiple lines in it, each being an email address. I have a button that when clicked should read the emails from the textbox and validate that they are working emails (no spelling errors or anything). How would I go about doing something like this? For context the textbox is called emailBox

VB:

Protected Sub SaveButton(sender As Object, e As EventArgs)

End Sub

Thank you all so much in advanced!


Solution

  • Hi there I'm guessing by spelling errors you just mean valid email syntax.

    You could use a regular expression. Like this:

    Protected Sub SaveButton(sender As Object, e As EventArgs)
        dim regexExpression As New Regex("^[_a-z0-9-]+(.[a-z0-9-]+)@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,4})$")
        'get an array of emails
        dim emails = emailBox.text.Split(",")
        'loop through emails checking each one
        For Each email in emails
            dim valid = regexExpression.IsMatch(email)
            'do whatever with result
        Next
    End Sub
    

    you will need to import this too, add it to the top of your file:

    Imports System.Text.RegularExpressions
    

    then the variable 'valid' will have a value of True or False that you can do what you like with.

    I have edited my answer, assuming you can use a comma to separate your emails.

    Edit 2: I can't guarantee the regex will work 100% correctly. Run your own tests, tweak it if need be or find/write another.