WHAT'S NEW?
Loading...

Validate email in VB.Net


Validate email address with Regular expression in VB.Net. However, the source code online, if I copy the code and paste it, I got an error. Absolutely, I found it.

I used Dim check As New System.Text.RegularExpressions.Regex(pattern, RegexOptions.IgnorePatternWhitespace)

And I imported:

Imports System.Text.RegularExpressions

Sample Screenshot
These simple lines of code determine the format of email address.

Imports System.Text.RegularExpressions
Public Class frmemail
    Private Sub btnok_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnok.Click
        Dim email As String
        Dim hold As String
        email = txtemail.Text        hold = IsValidEmail(email)
        If hold = True Then
            MessageBox.Show("Correct")        Else
            MessageBox.Show("Error")        End If
    End Sub
    ''' <summary>
    ''' method for determining is the user provided a valid email address
    ''' We use regular expressions in this check, as it is a more thorough
    ''' way of checking the address provided
    ''' </summary>
    ''' <param name="email">email address to validate</param>
    ''' <returns>true is valid, false if not valid</returns>
    Public Function IsValidEmail(ByVal email As String) As Boolean
        'regular expression pattern for valid email
        'addresses, allows for the following domains:
        'com,edu,info,gov,int,mil,net,org,biz,name,museum,coop,aero,pro,tv
        Dim pattern As String = "^[-a-zA-Z0-9][-.a-zA-Z0-9]*@[-.a-zA-Z0-9]+(\.[-.a-zA-Z0-9]+)*\." & _        "(com|edu|info|gov|int|mil|net|org|biz|name|museum|coop|aero|pro|tv|[a-zA-Z]{2})$"
        'Regular expression object
        'Dim check As New Text.RegularExpressions.Regex(pattern, RegexOptions.IgnorePatternWhitespace)'I modified this code
        Dim check As New System.Text.RegularExpressions.Regex(pattern, RegexOptions.IgnorePatternWhitespace)        'boolean variable to return to calling method
        Dim valid As Boolean = False
        'make sure an email address was provided
        If String.IsNullOrEmpty(email) Then
            valid = False
        Else
            'use IsMatch to validate the address
            valid = check.IsMatch(email)        End If
        'return the value to the calling method
        Return valid    End Function
End Class

1 comment: Leave Your Comments

  1. I have no idea about using regular expression yet! but many thanks your article posted here on how to create valid email using regular expression. I think this is very important to validate data for any kind of inputs from the users to determine if the user's fill the right information.

    Good job!

    ReplyDelete