EMail textbox validation

chidumca

Member
Joined
Mar 23, 2010
Messages
10
Programming Experience
Beginner
Hi,


I want to validate email in text box through key press event.my code is as follows

Private Sub Textbox5_Validating(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox5.Validating
Dim temp As String
temp = TextBox5.Text
Dim conditon As Boolean
emailaddresscheck(temp)
If emailaddresscheck(conditon) = False Then
MessageBox.Show("Enter your email address correctly", "Validation")

TextBox5.Text = ""
End If

End Sub

Private Function emailaddresscheck(ByVal emailaddress As String) As Boolean
Dim pattern As String = "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
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

Private Sub TextBox5_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox5.TextChanged
TextBox5.BackColor = Color.White
Dim temp As String
temp = TextBox5.Text
Dim conditon As Boolean
emailaddresscheck(temp)
If emailaddresscheck(conditon) = True Then
MessageBox.Show("Enter your email address correctly", "Validation")
TextBox5.Text = ""
End If
End Sub
it is not working,pls provide solutions....
 
Last edited:
1) If you are going to validate the email do it in one place - the validating event is fine.
2) use code tags so we can read the code better,
3) a function should return the boolean value,
VB.NET:
Private Function emailaddresscheck(ByVal emailaddress As String) As Boolean
   Dim pattern As String = "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
   Dim emailAddressMatch As Match = Regex.Match(emailaddress, pattern)
   If emailAddressMatch.Success Then
      Return True
   Else
      Return False
   End If
End Function
4) this function passes a string variable not a boolean,
5) why make a variable that = textbox5.Text just pass the textbox5.Text to the function,
Dim temp As String
temp = TextBox5.Text
6) why not name the textbox something meaningful like txtEmail.
 
What have you changed in your code since I posted? There were a few fixes for you to do. In the Validating event use the function's return value to set the e.Cancel property. This property will not let the textbox loss focus until the condition is met.
 
Back
Top