It is very common part of the web-application to include email address, and for this we require to validate if email address is correct and acceptable to save in database or not, so in this post, I have explained how we can validate email address in C# using regex and without using regex also (using data annotation in mvc).
Validate email address using regex in C#
When validating an email address using regex, you need to include namespace
System.Text.RegularExpressions
in your C# code, let's take a look at an example
using System;
using System.Text.RegularExpressions;
public class Program
{
public static void Main()
{
var EmailId1="test@gmail.com";
var EmailId2= "test1212@com";
string pattern = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";
//check first string
if (Regex.IsMatch(EmailId1 , pattern))
{
//if email is valid
Console.WriteLine(EmailId1+ " is a valid Email address ");
}
else
{
Console.WriteLine(EmailId1 + " is not a valid Email address");
}
//check second string
if (Regex.IsMatch(EmailId2 , pattern))
{
//print if email id is valid
Console.WriteLine(EmailId2+ " is Valid Email address ");
}
else
{
//print if email id is not valid
Console.WriteLine(EmailId2 + " is Not a Valid Email address");
}
}
}
Output:
test@gmail.com is a valid Email address
test1212@com is Not a Valid Email address
In the above code, we are using given regular expression to validate email address
string pattern = @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z";
Now, you can fine tune above code and add MX Record validation also using DNSClient Nuget package and MX Records of email using C# as below
// domain for example@gmail.com = gmail.com
public bool ValidateMXRecord(string domain, string mail)
{
var lookup = new LookupClient(IPAddress.Parse("8.8.4.4"), IPAddress.Parse("8.8.8.8"));
lookup.Timeout = TimeSpan.FromSeconds(5);
var result = lookup.Query(domain, QueryType.MX);
var records = result.Answers;
if (records.Any())
{
return true;
}
else
{
return false;
}
}
You might also like to read:
Verify email address exists or not? (With email id validation in C#)
Remote Validations in MVC (Check if Email id exists in database)
Validate email address using Data Annotation in MVC C# Model
We can also validate email address using EmailAddress data annotation in C# class, suppose here is my StudentModel.cs class
using System.ComponentModel.DataAnnotations;
namespace MVCValidateEmailAddress.Models
{
public class StudentModel
{
public string Name { get; set; }
[Required]
// data annotation to validate email in C#
[EmailAddress(ErrorMessage = "Enter valid Email address")]
public string EmailAddress { get; set; }
}
}
you need to include System.ComponentModel.DataAnnotations
namespace in your C# class to use EmailAddress data annotation.
Now when using this ViewModel inside MVC view, we can have code like this
@model MVCValidateEmailAddress.Models.StudentModel
@{
ViewBag.Title = "Home Page";
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewBag.Title - My ASP.NET Application</title>
@Styles.Render("~/Content/css")
</head>
<body>
<div class="container body-content">
@using (Html.BeginForm())
{
<div class="form-group">
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(model => model.Name, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor(m => m.EmailAddress)
@Html.TextBoxFor(model => model.EmailAddress, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.EmailAddress)
</div>
<button type="button" class="btn btn-success submit">Save</button>
}
</div>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
</body>
</html>
In the above code, we are using razor syntax to create html label using @Html.LabelFor()
and Textbox using @Html.TextBoxFor()
With the help of @Html.ValidationMessageFor (model=>model.EmailAddress)
we are showing validation error message from data annotation inside this html form.
As you can see we have referenced jQuery scripts <script src="~/Scripts/jquery-1.10.2.js"></script>
,<script src="~/Scripts/jquery.validate.js"></script>
, <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
, it is required to refer these files in your HTML page in order to make data annotation work.
Just build and run your project in brower, you will see output as below
That's it, if you have any questions, feel free to drop it below in comments section.
You may also like to read:
Verify email address exists or not? (With email id validation in C#)