Validate Email Address Using Regex in Visual Basic .NET

Tags: VB.NET, VB 2008, VB 2010, VB 2012, VB 2013

This tutorial describe how to validate an email address using regex in visual basic .net.

In the real world, you build an application that stores customers email address in your database. Before you submit the email entered to the database, you will validate it if it's a valid email address.

First add the following imports before your Public Class Form1

Imports System.Text.RegularExpressions

The following function checks email entered by the user.

Public Function validateEmail(emailAddress) As Boolean
        ' Dim email As New Regex("^(?<user>[^@]+)@(?<host>.+)$")
        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

Then call the above function when the user clicks on Submit Button

 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        If validateEmail(EmailTextBox.Text) = True Then
            MsgBox("Email is Valid")
			'proceed and save email
        Else
            MsgBox("Email is not Valid")
			
        End If
End Sub

One thing you need to keep in mind that the above function validates the email address against it's format. It doesn't check if the email account does exist or not.


Share This

Home | About | Contact | Privacy Policy

Copyright visual-basic-tutorials.com 2017 - All Rights Reserved.