It's not hard to do a email validation on a user entered textbox.
But this time I would to check if a string/paragraph contains email addresses
For example. I would like to check if there is email in the following string
"How are you today, please email me at [email protected] if you are interested"
Please help.
Here's how you can achieve this:
string para =
" kjqdshfkjsdfh dskjhskqjdfhk qdhjkdhfj kjhfksjdhf [email protected] jjhdjfhsfjjd jhjhjhj [email protected] ";
var splittedText = para.Split(new char[] {' '});
var mails = splittedText.Where(s => s.Contains("@"));
foreach (var mail in mails)
{
//here are all your mails
}
And then validate using the following method:
private bool IsEmailValid(string mail)
{
try
{
MailAddress eMailAddress = new MailAddress(mail);
return true;
}
catch (FormatException)
{
return false;
}
}
Or just use something like:
public static bool ValidateEmail(string str)
{
return Regex.IsMatch(str, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
}
First you split everything based on a whitespace delimiter (email addresses usually don't contain whitespaces):
var tokens = input.Split(" ");
Now you can validate the different tokens. The most easy one would be checking for an @ symbol and progressing from there. You could use an extensive regex, but you might as well just try and send an email to that address and see if it worked. It's a lot easier and doesn't require a 500-character regex.
Alternatively you can follow @Julie's advise and work with the MailAddress class.
As @Chris correctly remarks: an email address with a whitespace is valid if it is contained within quotes. Since it is a very uncommon edgecase, I would still hang on to this method and add a specific check to your code that validates the combination of quotes and whitespaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With