'Regular expression to validate comma separated email addresses?
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).
Solution 1:[1]
i dont know C# i can give an idea
split by ',' and validate each seperator..... its simple
Solution 2:[2]
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).
Solution 3:[3]
try this~
try {
Regex regexObj = new Regex(@"([A-Z0-9._%+-]+@(?:[A-Z0-9-]+\.)+[A-Z]{2,6},?)*", RegexOptions.IgnoreCase | RegexOptions.Multiline);
if (regexObj.IsMatch(subjectString)) {
// Successful match
} else {
// Match attempt failed
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
Solution 4:[4]
Try this,
private bool IsValidMultipleEmail1(string value)
{
Regex _Regex = new Regex(@"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
string[] _emails = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string email in _emails)
{
if (!_Regex.IsMatch(email))
return false;
}
return true;
}
Solution 5:[5]
Use the following regex, it will resolve your problem. The following regex will entertain post and pre spaces with comma too
/^((([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z\s?]{2,5}){1,25})*(\s*?,\s*?)*)*$/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | K6t |
| Solution 2 | |
| Solution 3 | Monday |
| Solution 4 | |
| Solution 5 | Irvin Dominin |
