Blog : Email address validation in vb.net

email address validation in vb.net


I'm trying to validate email address entered in a textbox, I want error message to be displayed when the user leave email address field with invalid email address "The email address is NOT valid."

This is what I have under a module:

Module Connection

Sub ValidateEmail(Byval mail as String)
Dim email as new System.Text.RegularExpressions.Regex("\S+@\S+\.\S+")

If email.IsMatch(mail) Then
Else
MsgBox("The Email is Not Valid",msgBoxStyle.Critical,"Invalid Email")
End If
End Sub

End ModuleThen I double click on the email textbox and put the following code:

If txtemail.text = " " Then
Else
ValidateEmail(txtemail.text)
End IfNow the thing is when I run my program, it doesn't allow me to finish entering email address, I enter first letter and it gives me error message "The Email is Not Valid", I want it to allow me to finish entering email address then when I move to the next field it can give me the message if the email is not valid.

Anyone who understand my problem here, please help

When you double click TextBox it creates TextBox_TextChanged eventhandler, which is fired every time the text changes inside textbox, instead you need to subscribe to the event which is fired when focus is lost on TextBox, that is TextBox_Leave. For subscribing to Leave event click F4 on TextBox and Properties window will open, navigate to Events tab, find Leave event and double click it

You could use the Onleave, and in the event of an error set focus back to the text box. You could skip checking for a valid format until a certain amount is entered in the Onchange, but do the full check onLeave.

Either of the above has knock on effects as presumably some later function needs email to be valid. So you'll need to check again before you try a send, or a save.

Or you could get rid of notification using a message box, say show an error image when it's invalid. The later functionality the depends on a valid pattern, could then simply check to see if the "error component" is visible. More like I'd you'd validate a form on web page.

The last one is my preference, not a big fan of message box errors