-1

I want to include email validation for my register form using regular expression

I've tried this code regex for validating my email

Dim ValidateEmail As Boolean
ValidateEmail = Regex.IsMatch(EmailAddress.Text, "^([\w]+)@([\w]+)\.([\w]+)$", RegexOptions.IgnoreCase)

I tried to input some email in my EmailAddress. The text which is my variable name, but I got an error after putting some dot ex: jannus.domingo@yahoo.com after Janus the dot is the error I got but after I removed dot on jannus.domingo@yahoo.com then it's fine.

Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • 3
    I know a lot of people speak highly of regex, but it's not always the most optimal solution. In this case you'd be better off looking for the @ symbol and that it ends in a well-known top level domain like .com, .net, etc because it's really hard to capture every possible email address with regex but it's easy to know all the TLDs – Richard Barker Oct 12 '19 at 16:49
  • http://web.archive.org/web/20090325234208/http://www.iamcal.com/publish/articles/php/parsing_email – Mary Oct 12 '19 at 17:55
  • [Regex Email validation](https://stackoverflow.com/q/5342375/7444103) – Jimi Oct 12 '19 at 19:55

1 Answers1

0

Instead of messing about with unreadable, long, hard and unmaintainable regular expression, simply try to create an instance of the MailAddress class with the string you get from the user. It will throw a FormatException if the format is invalid.

Here's a simple example:

Function IsEmailAddressWellFormatted(ByVal address As String) As Boolean
    Try
        Dim address = New MailAddress(address)
        Return True
    Catch ex As FormatException
        Return False 
        ' We don't care about the actual exception here, 
        ' the fact that it's thrown is enough to know the string is not a valid format.
    End Try
End Function
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121
  • [Glad to help :-)](http://meta.stackoverflow.com/questions/291325/how-to-show-appreciation-to-a-user-on-stackoverflow/291327#291327) – Zohar Peled Oct 17 '19 at 06:15