Verifier email c# code
Here is an example of C# code that verifies an email address using a regular expression:
using System.Text.RegularExpressions;
public bool IsValidEmail(string email)
{
string pattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$";
Regex regex = new Regex(pattern);
return regex.IsMatch(email);
}
This code uses a regular expression to match the email address. The regular expression pattern is:
^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$
This pattern matches:
^
matches the start of the string[a-zA-Z0-9._%+-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-), underscore (_), percent (%), plus sign (+)@
matches the @ symbol[a-zA-Z0-9.-]+
matches one or more of the following characters: letters (both uppercase and lowercase), numbers, dot (.), hyphen (-)\.
matches a period (.) character[a-zA-Z]{2,}
matches the domain extension (it must be at least 2 characters long)$
matches the end of the string
You can use this method like this:
string email = "[email protected]";
if (IsValidEmail(email))
{
Console.WriteLine("Email is valid");
}
else
{
Console.WriteLine("Email is not valid");
}
Note that this is not foolproof and there are many ways to validate an email address. This code only checks for basic syntax and does not check if the email address actually exists or is valid.
You can also use System.Net.Mail.MailAddress
class to validate email address:
using System.Net.Mail;
public bool IsValidEmail(string email)
{
try
{
MailAddress addr = new MailAddress(email);
return true;
}
catch
{
return false;
}
}
This code creates a new MailAddress
object with the provided email address and checks if it is valid. If the email address is valid, the method returns true
, otherwise it returns false
.