0

I am developing an email validation and wanting to check if there has is more than 1 @ symbol in the email, how do i go on about implementing this?

static string Check(string email)
    {
        
        if (email.Contains("@") && email.Contains("."))
        {
          // check for 2 @ symbols or more will be here

            
         return email;
        }

        return string.Empty;
    }
jeremy.o
  • 73
  • 5
  • 1
    Use an available regex for this(or the `MailAddress` constructor), don't reinvent the wheel. https://emailregex.com/ – Tim Schmelter Jan 27 '22 at 10:33
  • Maybe use `.GroupBy`? Or `.IndexOf` to find the first one and `.IndexOf` with the initial offset to see if there is another. Or use Regex. – ProgrammingLlama Jan 27 '22 at 10:34
  • Does this answer your question? [How would you count occurrences of a string (actually a char) within a string?](https://stackoverflow.com/questions/541954/how-would-you-count-occurrences-of-a-string-actually-a-char-within-a-string) – Liam Jan 27 '22 at 10:35

1 Answers1

2

In general you should not reinvent the wheel, especially not with a complex topic like email validation. Use an available regex or the MailAddress constructor.

However, to answer your question, if you really need something like that (for other tasks) you could implement an extension method like this:

public static IList<int> AllIndexOf(this string text, string str, StringComparison comparisonType)
{
    IList<int> allIndexOf = new List<int>();
    int index = text.IndexOf(str, comparisonType);
    while(index != -1)
    {
        allIndexOf.Add(index);
        index = text.IndexOf(str, index + 1, comparisonType);
    }
    return allIndexOf;
}

with this it's easy:

if(email.AllIndexOf("@", StringComparison.OrdinalIgnoreCase).Count > 1)
{
    // ...
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939