Reputation: 1
Currently I am using below code to validate email
public static bool IsValidEmail(string email)
{
var r = new Regex(@"^([0-9a-zA-Z]([-\.\'\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$");
return !string.IsNullOrEmpty(email) && r.IsMatch(email);
}
Now want to validate this "[email protected]" email as valid email id. what change needs to be done in regex?
Upvotes: 0
Views: 2676
Reputation: 71
Using this Regex is not the best way to validate an Email.
But, correcting your Regex to the pattern you asked, it would be like this:
var r = new Regex(@"^([0-9a-zA-Z]([-\.\'\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z\.])+[.a-zA-Z]{2,9})$");
Still insisting on the regex, you can find a more complete pattern in: https://www.ex-parrot.com/pdw/Mail-RFC822-Address.html
I encourage you to use Microsoft documentation for email address as suggested by @Jeremy Lakeman -> https://learn.microsoft.com/en-us/dotnet/api/system.net.mail.mailaddress.trycreate?view=net-5.0
Upvotes: 3