Server side C# VB.Net Email Address Validation in Asp.Net apsx page

In my previous post i have described “How to validate an Email address from client side using Javascript & Regular Expression“. In this post i will describe “How to validate Email Address from Server side code C# or VB.Net using Regular expression”. Because both client side & server side validation provides us good security. For reusability purpose here I am using a static class for all sorts of validation.


So first add a static Class named clsValidation under APP_Code Folder:
C# Code:

    public const string EmailStandard = @"^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$";
    public static bool ValidateEmail(string emailID)
        if (emailID != null)
            return System.Text.RegularExpressions.Regex.IsMatch(emailID, EmailStandard);
            return false;

VB.Net Code:

    Public Const EmailStandard As String = "^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$"
    Public Shared Function ValidateEmail(emailID As String) As Boolean
        If emailID <> "" Then
            Return System.Text.RegularExpressions.Regex.IsMatch(emailID, EmailStandard)
            Return False
        End If
    End Function

Now add HTML markup Like Below:

    <asp:TextBox ID='txtEmail' runat="server"></asp:TextBox>
    <asp:Label runat="server" ID="lbl" Font-Bold="true"></asp:Label>
    <br />
    <asp:Button id="cmdCheck" runat="server" Text="Validate Email" 

Now test the Regular Expression from Code Behind:
C# Code:

    protected void cmdCheck_Click(object sender, EventArgs e)
        if (clsValidation.ValidateEmail(txtEmail.Text))
            //Valid Email
            // You can save registration form data into database
            lbl.Text = "Email Address is Valid !";
            //Invalid Email
            //Notify user
            lbl.Text = "Email Address is not Valid !";

VB.Net Code:

    Protected Sub cmdCheck_Click(sender As Object, e As System.EventArgs)
        If clsValidation.ValidateEmail(txtEmail.Text) Then
            'Valid Email
            'You can save registration form data into database
            lbl.Text = "Email Address is Valid !"
            'Invalid Email
            'Notify user
            lbl.Text = "Email Address is not Valid !"
        End If
    End Sub

Now run the project. Hope everything will be fine. If any problem download full source code from below:

Download Code Example C#        Download Code Example VB.Net

Posted in .Net,, C#, VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *