Validate Email Address using Regular Expression from code behind in ASP.Net

vereato
 
on Jun 20, 2021 10:11 PM
Sample_688229.zip
2662 Views

Hi there

Its possible to change this from html to VB.Net 

i want to use this as classes and not using on the page 

Validate Email Address using Regular Expression Validator in ASP.Net

thanks

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jun 21, 2021 04:09 AM

Hi vereato,

Check this example. Now please take its reference and correct your code.

HTML

<asp:TextBox ID="txtEmail" runat="server" />
<asp:Label ID="lblMessage" runat="server" ForeColor="Red" Visible="false"></asp:Label>
<br />
<br />
<asp:Button Text="Submit" runat="server" OnClick="OnSubmit" />

Code

C#

protected void OnSubmit(object sender, EventArgs e)
{
    lblMessage.Visible = false;
    lblMessage.Text = "";
    if (!string.IsNullOrEmpty(txtEmail.Text.Trim()))
    {
        System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        bool isValid = regex.IsMatch(txtEmail.Text.Trim());
        if (!isValid)
        {
            lblMessage.Visible = true;
            lblMessage.Text = "Invalid email address";
        }
    }
    else
    {
        lblMessage.Visible = true;
        lblMessage.Text = "Required";
    }
}

VB.Net

Protected Sub OnSubmit(ByVal sender As Object, ByVal e As EventArgs)
    lblMessage.Visible = False
    lblMessage.Text = ""
    If Not String.IsNullOrEmpty(txtEmail.Text.Trim()) Then
        Dim regex As Regex = New Regex("^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$")
        Dim isValid As Boolean = regex.IsMatch(txtEmail.Text.Trim())

        If Not isValid Then
            lblMessage.Visible = True
            lblMessage.Text = "Invalid email address"
        End If
    Else
        lblMessage.Visible = True
        lblMessage.Text = "Required"
    End If
End Sub

Screenshot