-1

I have the following code to validate the email. It worked well if only simple text is entered. But when I am entering the partial text say test@ only it doesn't throws exception. Can you please guide me what am I missing.

Try
    Dim M As New System.Net.Mail.MailAddress(Txt_Email.Text)
Catch ex As FormatException
    MsgBox(ex.Message, MsgBoxStyle.Critical + MsgBoxStyle.OkOnly)
    Txt_Email.Text = string.Empty
Exit Sub
End Try

Thanks in Adavance

Omer

Max
  • 12,622
  • 16
  • 73
  • 101
Omer
  • 13
  • 1
  • 1
  • 6

1 Answers1

0

You could implement a simple check, validating the given e-mail adres like:

Public Function EmailIsValid(emailaddress As String) As Boolean
    Try
        Dim address = New MailAddress(emailaddress)
        Return True
    Catch ex As Exception
        Return False
    End Try
End Function

Call it like:

Dim result as Boolean = EmailIsValid(Txt_Email.Text)

result will be filled with true if this is a valid e-mailaddress and will be filled with false if it isn't. But, there are better ways checking if an emailaddress is valid. Perhaps using Regex.

The way I mentioned above isn't that good, since manipulating code using try/catch is a bad idea.

A Regex way of doing this can be found here: Using a regular expression to validate an email address

Community
  • 1
  • 1
Max
  • 12,622
  • 16
  • 73
  • 101