.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,504 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Hi,
I have editor and user insert multi emails sepertated by semicolon .
I need to validate them.
method?
/// <summary>
/// Check if email reciepents is valid
/// </summary>
/// <param name="reciepents">The reciepents seperated by coma(;)</param>
/// <returns>Return true if reciepents string is valid, otherwise return false</returns>
public static bool IsValidReciepents(string reciepents)
{
try
{
if (string.IsNullOrEmpty(reciepents))
{
return false;
}
string[] tmpEmails = reciepents.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (var address in tmpEmails.Select(s => s.Trim()).Distinct(StringComparer.InvariantCultureIgnoreCase).ToArray())
{
var isEmailValid = IsValidEmail(address);
if (!isEmailValid)
{
return false;
}
}
return true;
}
catch (Exception ex)
{
_logger.Error("IsValidReciepents", ex);
return false;
}
}
/// <summary>
/// Check if input string is valid
/// </summary>
/// <param name="inputString">The input string to check</param>
/// <returns>Return true if input string is valid, otherwise return false</returns>
public static bool IsValidEmail(string inputString)
{
try
{
MailAddress mailAddress = new MailAddress(inputString);
return true;
}
catch(Exception ex)
{
return false;
}
}
Thanks in advance,
It depends on how many emails you need to validate. If they're just a few, you can use MailAddres or even use a Regular Expression for it.
var pattern = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";
if(Regex.IsMatch(val ?? "", pattern))
// Do what you want
Another thing to think about is throw an exception... Do you really need it? All exceptions have a cost, so can be more efficient just do nothing.
Here's a complete example
// Let's supose you already have a property Email being filled with addresses separated by coma
public void OnSubmit()
{
const string pattern = @"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";
var validEmails = new List<string>();
foreach(var item in Email.Split(","))
{
if(Regex.IsMatch(item ?? "", pattern))
validEmails.Add(item);
}
// Now you have a list with only valid emails
...
}