C# code to validate email address
What about this?
bool IsValidEmail(string email)
{
var trimmedEmail = email.Trim();
if (trimmedEmail.EndsWith(".")) {
return false; // suggested by @TK-421
}
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == trimmedEmail;
}
catch {
return false;
}
}
Per Stuart's comment, this compares the final address with the original string instead of always returning true. MailAddress tries to parse a string with spaces into "Display Name" and "Address" portions, so the original version was returning false positives.
To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.
Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:
- cog@wheel
- "cogwheel the orange"@example.com
- 123@$.xyz
For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answer to this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.
Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow as an email address."
As for using exception handling for business logic, I agree that is a thing to be avoided. But this is one of those cases where the convenience and clarity may outweigh the dogma.
Besides, if you do anything else with the e-mail address, it's probably going to involve turning it to a MailAddress. Even if you don't use this exact function, you will probably want to use the same pattern. You can also check for specific kinds of failure by catching different exceptions: null, empty, or invalid format.
--- Further reading ---
Documentation for System.Net.Mail.MailAddress
Explanation of what makes up a valid email address
How to validate email in c#
You can create a variable for pattern.
@{
var pattern = "/^[a-z0-9._%+-]+@@[a-z0-9.-]+.[a-z]{2,4}$/";
}
<input type="text" ng-model="Email" id="txtEmail" ng-pattern="@pattern" name="Email" placeholder="Email" required>
Regex Email validation
TLD's like .museum aren't matched this way, and there are a few other long TLD's. Also, you can validate email addresses using the MailAddress class as Microsoft explains here in a note:
Instead of using a regular expression to validate an email address,
you can use the System.Net.Mail.MailAddress class. To determine
whether an email address is valid, pass the email address to the
MailAddress.MailAddress(String) class constructor.
public bool IsValid(string emailaddress)
{
try
{
MailAddress m = new MailAddress(emailaddress);
return true;
}
catch (FormatException)
{
return false;
}
}
This saves you a lot af headaches because you don't have to write (or try to understand someone else's) regex.
EDIT: For those who are allergic to try/catch: In .NET 5 you can use MailAddress.TryCreate
. See also https://stackoverflow.com/a/68198658, including an example how to fix .., spaces, missing .TLD, etc.
C# code to validate email address
What about this?
bool IsValidEmail(string email)
{
var trimmedEmail = email.Trim();
if (trimmedEmail.EndsWith(".")) {
return false; // suggested by @TK-421
}
try {
var addr = new System.Net.Mail.MailAddress(email);
return addr.Address == trimmedEmail;
}
catch {
return false;
}
}
Per Stuart's comment, this compares the final address with the original string instead of always returning true. MailAddress tries to parse a string with spaces into "Display Name" and "Address" portions, so the original version was returning false positives.
To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.
Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:
- cog@wheel
- "cogwheel the orange"@example.com
- 123@$.xyz
For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answer to this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.
Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow as an email address."
As for using exception handling for business logic, I agree that is a thing to be avoided. But this is one of those cases where the convenience and clarity may outweigh the dogma.
Besides, if you do anything else with the e-mail address, it's probably going to involve turning it to a MailAddress. Even if you don't use this exact function, you will probably want to use the same pattern. You can also check for specific kinds of failure by catching different exceptions: null, empty, or invalid format.
--- Further reading ---
Documentation for System.Net.Mail.MailAddress
Explanation of what makes up a valid email address
Best way to validate email address format in C#
Validating email addresses is a complicated task, and writing code to do all the validation up front would be pretty tricky. If you check the Remarks
section of the MailAddress
class documentation, you'll see that there are lots of strings that are considered a valid email address (including comments, bracketed domain names, and embedded quotes).
And since the source code is available, check out the ParseAddress
method here, and you'll get an idea of the code you'd have to write to validate an email address yourself. It's a shame there's no public TryParse
method we could use to avoid the exception being thrown.
So it's probably best to just do some simple validation first - ensure that it contains the minimum requirements for an email address (which literally appears to be user@domain
, where domain
does not have to contain a '.'
character), and then let the exception handling take care of the rest:
foreach (var userID in recipientUserIds)
{
var userInfo = GetUserInfo(userID);
// Basic validation on length
var email = userInfo?.Email1?.Trim();
if (string.IsNullOrEmpty(email) || email.Length < 3) continue;
// Basic validation on '@' character position
var atIndex = email.IndexOf('@');
if (atIndex < 1 || atIndex == email.Length - 1) continue;
// Let try/catch handle the rest, because email addresses are complicated
MailAddress to;
try
{
to = new MailAddress(email, $"{userInfo.FirstName} {userInfo.LastName}");
}
catch (FormatException)
{
continue;
}
using (MailMessage message = new MailMessage(from, to))
{
// populate message and send email here
}
}
Validating an email address
You could just split the email string on the comma and validate each email address using a simple (or huge) email regex. Or, try creating a MailAddress
object; it supports some basic validation of the address too.
How to validate email address in c# console application?
using System;
using System.Collections.Generic;
class Demo {
static void Main() {
string val;
bool validEmail = false;
Console.Write("Enter Email: ");
val = Console.ReadLine();
int stringSplitCount = val.Split('@').Length;
if(stringSplitCount > 1 && stringSplitCount <= 2) // should only have one @ symbol
{
stringSplitCount = val.Split('.').Length;
if(stringSplitCount > 1) // should have at least one . (dot)
validEmail = true
}
val += (validEmail ? " is valid" ; "is invalid");
Console.WriteLine("Your input: {0}", val);
}
}
Best Regular Expression for Email Validation in C#
Email address: RFC 2822 Format
Matches a normal email address.
Does not check the top-level domain.
Requires the "case insensitive"
option to be ON.
[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?
Usage :
bool isEmail = Regex.IsMatch(emailString, @"\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", RegexOptions.IgnoreCase);
Related Topics
Set Focus on Textbox in Wpf from View Model
Redirecttoaction With Parameter
Unity: Null While Making New Class Instance
How Is Generic Covariance & Contra-Variance Implemented in C# 4.0
How Should the Viewmodel Close the Form
Split a String by Another String in C#
How to Update the Current Line in a C# Windows Console App
Generating Random, Unique Values C#
How to String.Format a Timespan Object With a Custom Format in .Net
Linq to Entities Case Sensitive Comparison
Question About Terminating a Thread Cleanly in .Net
Access the Current Httpcontext in ASP.NET Core
Entity Framework .Remove() Vs. .Deleteobject()
Deserializing Json Data to C# Using Json.Net
Simple and Tested Online Regex Containing Regex Delimiters Does Not Work in C# Code