Welcome to deBUG.to Community where you can ask questions and receive answers from Microsoft MVPs and other experts in our community.
1 like 0 dislike
6k views
in .Net Framework by 5 5 8
I am new to ASP.NET and I just need to validate if the provided text in a textbox is a correct email address using C# in ASP.NET?

1 Answer

2 like 0 dislike
by 159 200 385
selected by
 
Best answer

Validate Email in ASP.NET

You can easily validate an Email Address without using any kind of code using Regular Expressions control in ASP.NET as the following:

  1. In your Project, Add a Regular Expression Validator from the toolbox.
  2. Click on your Regular Expression Validator control, then click on "F4" to open its properties.
  3. In the properties, click on Validation Expression, then select Internet E-Mail Address.
    Regular expression editor in asp.net
  4. After that, make sure you have set the following properties:
    • ControlToValidate
    • ValidationGroup
    • ErrorMessage

Output

<asp:TextBox ID="txt_email"  runat="server"/>
<asp:RegularExpressionValidator ID="EmailValidator" runat="server" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txt_email" ErrorMessage="Invalid Email Address" ValidationGroup="Group1"></asp:RegularExpressionValidator>

Besides the above method, you can also use the below function to validate Email Address using C# as below

   public bool EmailAddressValidator(string email)
    {
        if (new EmailAddressAttribute().IsValid(email) && !string.IsNullOrEmpty(email))
            return true;
        else
            return false;
    }
If you don’t ask, the answer is always NO!
...