Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 438
  • Last Modified:

How to validate textbox for email in vb.net

I have vb.net windows form.
A textbox txtemail is there.
The email is optional.
But i want once email is being entered it should validate correct email address.
0
searchsanjaysharma
Asked:
searchsanjaysharma
1 Solution
 
plusone3055Commented:
http://www.vbforums.com/showthread.php?t=407441

Imports System.Text.RegularExpressions

    Function EmailAddressCheck(ByVal emailAddress As String) As Boolean

        Dim pattern As String = "^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$"
        Dim emailAddressMatch As Match = Regex.Match(emailAddress, pattern)
        If emailAddressMatch.Success Then
            EmailAddressCheck = True
        Else
            EmailAddressCheck = False
        End If

    End Function
0
 
nepaluzCommented:
You can use Regex
Dim ErP As New ErrorProvider
If TextBox1.Text <> "" Then
    Dim rex As Match = Regex.Match(Trim(TextBox1.Text), "^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,3})$", RegexOptions.IgnoreCase)
    If rex.Success = False Then
        ErP.SetError(TextBox1, "Please Enter a valid Email-Address")
    Else
        ErP.SetError(TextBox1, String.Empty)
    End If
End If

Open in new window

0
 
käµfm³d 👽Commented:
Ah the age old question:  "How do I validate email addresses..."  You can really only validate structure. There is no way in code to tell if an email address is valid or not. Even if you attempt to send a message, the server is the entity which will receive the response. If for some reason you need to know whether or not the actual address is "live", then you will need to come up with some scheme to verify (maybe check against AD if you are on a LAN).

As far as checking structure, the typical solution is to run the value against a regular expression (regex). In the link I referenced, you will see a few different examples of expressions you might use. Each has benefits and drawbacks. If you decide to use regex for this purpose, then whichever pattern you use, you can use logic such as this to validate the address:

Dim emailIsValid As Boolean = System.Text.RegularExpressions.Regex.IsMatch(txtEmail.Text, "[pattern you chose]")

Open in new window


Again, the regex approach only validates structure. It cannot tell you whether or not an account, or even a domain exists.
0
 
searchsanjaysharmaAuthor Commented:
ok
0

Featured Post

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now