0

I have a question regarding email verification in (Visual) C#.

I searched the web and found several methods to do so. E.g. here:

Strangely both of them seem to let emails like "ex.as@asd,com" pass (notice the comma instead of a point).

However, if I try to send an email via SmtpClient object I get an exception because the given email address has the wrong format.

Any ideas?

Community
  • 1
  • 1
TheElk
  • 1
  • 5
  • 4
    I can be pretty difficult to validate an email address. Since your SMTP client is really the one who ends up deciding what is valid you should use it as your validator. http://stackoverflow.com/a/1374644/1341538 This post shows a good example. – Andres Castro Jul 31 '15 at 14:48
  • 1
    Use the simple regex in *accepted* answer. http://stackoverflow.com/questions/13719821/email-validation-using-regular-expression-in-php – EZI Jul 31 '15 at 14:48
  • I am really sorry they worked.... I just edited the validation at the wrong point in my program. Never the less thanks for all your usefull answers! – TheElk Jul 31 '15 at 15:07

2 Answers2

0

If you try below it will throw an exception in a way that you could validate the address.

try 
{
    address = new MailAddress("ex.as@asd,com", "Email validation").Address;
} 
catch(FormatException) {
    //Invalid email address
}

MailAdress.Address property throws FormatException when you try to get it.

CharithJ
  • 46,289
  • 20
  • 116
  • 131
0

Regex from first link is working for me. You should replace all \ to \\ and " to \".

I tried this code:

var validateEmailRegex = new Regex("(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])");
var isValidEmail = validateEmailRegex.Match("ex.as@asd,com").Success;

And i got isValidEmail == false.

Vadim Pashkov
  • 519
  • 6
  • 8