Validating Email Address Using Regex or Regular Expression

A tutorial validating email address through textbox using Visual Basic .NET, So it is more on detecting the ‘@’ and the ‘.’ Symbol.

Open your Visual Basic .NET Application.

Step 1:
Create a New Project, go to File Menu and navigate to New > Project then name it ValidateEmail (see Image below)


Step 2:
Next, Add a New Form by navigating in Project Menu and Click Add Windows Form. You can change the name of your form if you want (optional).
Step 3: Add 1 Label, 1 Button and 1 TextBox (Please refer the image below).


Label Property
Name: Label1
Text: Validate Email:

TextBox Property
Name: txtEmail

Button Property
Name: btnValidate
Text: Validate

Then go to your code editor and paste this code.

Imports System.Text.RegularExpressions
Public Class frmValidateEmail

    'Validate Email Address Using Regex
    Public Function validateEmail(ByVal emailAddress) As Boolean
        Dim email As New Regex("([\w-+]+(?:\.[\w-+]+)*@(?:[\w-]+\.)+[a-zA-Z]{2,7})")
        If email.IsMatch(emailAddress) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnValidate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnValidate.Click
        If validateEmail(txtEmail.Text) = True Then
            MsgBox("Email is Valid")
            'proceed and save email
        Else
            MsgBox("Email is not Valid")
        End If
    End Sub
End Class
Final runtime output:


Enjoy!!
Validating Email Address Using Regex or Regular Expression Validating Email Address Using Regex or Regular Expression Reviewed by code-dev on 1:28 PM Rating: 5

No comments:

Powered by Blogger.