How to validate email in .Net c#/vb.net

Validation becomes a basic task in any form of application development especially the email validation which is required by any web application that allows user registration.

The following code sample is utilizing the regular expression pattern to validate the email address. If you have any other way of validating emails, please comment below.

C# sample

public static bool IsEmail(string strIn)
{
      if (string.IsNullOrEmpty(strIn))
           return false;
 
      return Regex.IsMatch(strIn,
             @"^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?             @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$");
}

 
VB.Net Sample

Public Shared Function IsEmail(strIn As String) As Boolean
    If String.IsNullOrEmpty(strIn) Then
        Return False
    End If
 
    Return Regex.IsMatch(strIn, "^(?("")("".+?""@)|(([0-9a-zA-Z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-zA-Z])@))" & "(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,6}))$")
End Function
Advertisements