Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to validate comma separated email addresses?

Tags:

c#

regex

asp.net

I need to validate email addresses which can be single or several comma-separated ones.

Before I was using in a regular expression validator an expression like:

string exp = @"((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*";

and it was validating multiple or one single email address.

But same expression is not valdiating in C#? It says valid to invalid addresses as well.

Please correct me or suggest me an expression to validate email addresse(s).

like image 434
user576510 Avatar asked Jul 29 '11 08:07

user576510


3 Answers

Please give more details. Which addresses are matched as valid, but should be invalid? How do you call the regex (your c# code)?

A point I see is that you are missing anchors.

 ^((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([,])*)*$

^ matches the start of the string

$ matches the end of the string

If you don't use them your pattern will match as soon as it found a valid sub string.

like image 159
stema Avatar answered Nov 15 '22 01:11

stema


i dont know C# i can give an idea split by ',' and validate each seperator..... its simple

like image 32
K6t Avatar answered Nov 14 '22 23:11

K6t


Without knowing how you're doing the validation, it's hard to tell why C# is validating some strings that the validator had rejected. Most probably it's because the validator is looking at the entire string, and you're using Regex.IsMatch() in C# which would also accept the match if a substring matches. To work around that, add \A to the start and \Z to the end of your regex. In your case, the entire regex is optional (enclosed by (...)*) so it also matches the empty string - do you want to allow that?

Then again, you might want to reconsider the regex approach entirely - no sane regex can validate e-mail addresses correctly (and you'll still pass addresses that just look valid but don't have an actual account associated with them).

like image 26
Tim Pietzcker Avatar answered Nov 15 '22 00:11

Tim Pietzcker