|
-
Mar 7th, 2012, 02:40 PM
#1
Thread Starter
Frenzied Member
[RESOLVED] Email address validation with RegEx
Hello.
I have been using a function to validate email addresses for awhile now. Yesterday i discovered that the code indicates that 2 different email addresses are invalid when in reality they are perfectly fine.
The code uses RegEx to determine if an email address is valid. I have tried to understand RegEx, but I can never seem to figure it out. Here is the code:
Code:
Private Sub btnCheckEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckEmail.Click
If ValidateEmailAddress(txtEmail.Text) = True Then
lblResult.Text = "Valid !"
Else
lblResult.Text = "X - BAD EMAIL - X"
End If
Beep()
End Sub
''' <summary>
''' Use this function to check an email address to ensure it is in the proper format.
''' (It has an @ symbol, has a suffix to the domain name (ie: .com), does not contain any spaces, etc)
''' </summary>
''' <param name="sCheckEmailAddress">The email address to be checked.</param>
''' <returns>This function returns a boolean value. True is the email address is valid, False if it is not.</returns>
Public Function ValidateEmailAddress(ByVal sCheckEmailAddress As String) As Boolean
Try
sCheckEmailAddress = Trim$(sCheckEmailAddress)
Return Regex.IsMatch(sCheckEmailAddress, "^[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]$")
Catch Exp As Exception
Return False
End Try
End Function
Using that function, these 2 email addresses are flagged as being invalid:
[email protected]
[email protected]
How can the RegEx be re-written to allow the local part (before the @ symbol) to be 1 character, and/or be a number? I understand the "a-z" part, but i don't understand what [\w\.-] means, or why the a-z is duplicated before the @ symbol.
.
~Peter

-
Mar 7th, 2012, 02:58 PM
#2
Re: Email address validation with RegEx
Try
vb Code:
Option Strict On Imports System.Text.RegularExpressions Public Class MainForm Private Function ValidateEmailAddress(ByVal sCheckEmailAddress As String) As Boolean Return Regex.IsMatch(sCheckEmailAddress, "^([\w-]+\.)*?[\w-]+@[\w-]+\.([\w-]+\.)*?[\w]+$") End Function Private Sub btnCheckEmail_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCheckEmail.Click If ValidateEmailAddress(txtEmail.Text) Then lblResult.Text = "Valid !" Else lblResult.Text = "X - BAD EMAIL - X" End If End Sub End Class
-
Mar 7th, 2012, 03:36 PM
#3
Thread Starter
Frenzied Member
Re: Email address validation with RegEx
That works!
I still can't figure out the RegEx, but all the tests i ran came back valid when it should, and invalid when i entered bad email addresses.
Thank you.
~Peter

Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|