Skip to main content

How to Create an Email Validation TextBox in C#.


In this tutorial, I will teach you how to create an email validation textbox using c#. This method has the ability to verify the correct email format in a textbox. This is very helpful when you are dealing with the registration form. See the procedure below to see how it works.

Creating Application

Step 1

Open Microsoft Visual Studio 2015 and create a new windows form application for c#.
ps1

Step 2

Do the form just like shown below.
ps2

Step 3

Press F7 to open the code editor. In the code editor , add a namespace to access regular expression libraries.

  1.  
  2. using System.Text.RegularExpressions;

Step 4

Create a method for an email validation.

  1.  
  2. private static Regex email_validation()
  3. {
  4. string pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
  5. + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
  6. + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";
  7.  
  8. return new Regex(pattern, RegexOptions.IgnoreCase);
  9. }

Step 5

Initialize the method that you have created.

  1.  
  2. static Regex validate_emailaddress = email_validation();

Step 6

Write the following code to validate an email in a textbox when the button is clicked.

  1.  
  2. private void button1_Click(object sender, EventArgs e)
  3. {
  4. if (validate_emailaddress.IsMatch(textBox1.Text) != true)
  5. {
  6. MessageBox.Show("Invalid Email Address!", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
  7. textBox1.Focus();
  8. return;
  9. }else
  10. {
  11. MessageBox.Show("Email Address is valid.");
  12. }
  13.  
  14. }

For any questions about this article. You can contact me @
Email – [email protected]
Mobile No. – 09305235027 – TNT
Or feel free to comment below.

Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.