In this article I will explain with an example, how to perform Email Validation using Regular Expression in C# and VB.Net.
The User will enter Email Address in TextBox and when the Button is clicked, the Email Address will be tested against the Regular Expression and if invalid, a Message Box will be displayed.
Form Design
The Form consists of a TextBox control and a Button. The Button has been assigned Click event handler.
Namespaces
You will need to import the following namespace.
C#
using System.Text.RegularExpressions;
VB.Net
Imports System.Text.RegularExpressions
Validate Email Address in TextBox using Regular Expression in C# and VB.Net
When the Button is clicked, the Email Address from the TextBox is tested against the Regular Expression using the IsMatch function.
If the Email Address is found invalid an error message is displayed using MessageBox.
C#
private void btnValidate_Click(object sender, EventArgs e)
{
Regex 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})(\]?)$");
bool isValid = regex.IsMatch(txtEmail.Text.Trim());
if (!isValid)
{
MessageBox.Show("Invalid Email.");
}
}
VB.Net
Private Sub btnValidate_Click(sender As System.Object, e As System.EventArgs) Handles btnValidate.Click
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
MessageBox.Show("Invalid Email.")
End If
End Sub
Screenshot
Downloads