Regular expression for validating email in .net

Regular expressions are a good way to validate text fields such as names, Email address, phone numbers, and other user information. You can use them to constrain input, apply formatting rules, and check lengths.

You can use the System.Text.RegularExpressions.Regex class for validate any input string for any specific format.

Following example shows that how to validate email address

[C#]

using System.Text.RegularExpressions;
 
public static bool CheckEmail(string stremail)
 
        {
 
            string MatchEmailPattern = "^[\\w\\.\\-]+@[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]{1,})*(\\.[a-zA-Z]{2,3}){1,2}$";
 
            if (stremail != null) return Regex.IsMatch(stremail, MatchEmailPattern);
 
            else return false;
 
        }

 

[VB.NET]

Public Shared Function CheckEmail(ByVal stremail As String) As Boolean
 
        Dim MatchEmailPattern As String = "^[\w\.\-]+@[a-zA-Z0-9\-]+(\.[a-zA-Z0-9\-]{1,})*(\.[a-zA-Z]{2,3}){1,2}$"
 
        If stremail IsNot Nothing Then
 
            Return Regex.IsMatch(stremail, MatchEmailPattern)
 
        Else
 
            Return False
 
        End If
 
    End Function
  • mohit

    sir pls say how to store all validation control means address ,email,url validation in one method .