-1

I can't get the logic of this problem from my mind. Will you help me, pls?

I make a manual email validation for practice. So, in email validation there's a validation that states: "@ is cannot be more than one."

I'm stuck from here:

            int atValidation = 0;
        for (int i = 0; i < txtEmail.Text.Length; i++)
        {
            if (Char.IsSymbol('@'))
            {
                atValidation++;
            }
        }

I'm sorry if my question is confusing, I can only explain like this vvv
Example:
Input Email |_______|
Input Email | rich@rd@aha.com |
message box: '@' cannot be more than one
Input Email | richard@aha.com |
message box: email is valid

3 Answers3

1

There are many more rules for email validation, but if all you want to do is check for a single @ sign, you could get all of the @ characters and check the count

if (txtEmail.Text.ToCharArray().Where(x => x == '@').Count() != 1)
{
     //email is invalid
}
Broom
  • 596
  • 2
  • 18
1

There are other better ways to validate email for example MailAddress class and regex.

You can find examples here:

MailAddress: Regex Email validation

regex: Best Regular Expression for Email Validation in C#

Community
  • 1
  • 1
Vivek Sharma
  • 1,912
  • 1
  • 13
  • 15
1

There are a few ways you can do this. The first example I show below is a "straight" LINQ query and the second is an extension method that uses a loop. (Extension methods, in case you're not familiar, are a way of "adding" a method to class without modifying the original code; it's a Decorator Pattern).

LINQ Query approach:

int count = email.Count(c => c == '@');

This will give you the number of times that the '@' symbol appears. If count > 1 you know that there are duplicates. (Actually, you'd expect "count" to be exactly 1; if it's 0 there's no '@' symbol at all).

The downsides of the above solution are that it isn't very flexible (if you wanted to implement more rules you'd effectively be doing more loops, which isn't all that efficient) and that it'll always go through the entire string; it's not "smart enough" to know that it can stop counting once count == 2.

Here's another one:

public static class LinqExtensions
{
    public static bool ContainsMultiple<T>(this IEnumerable<T> enumerable, T item)
    {
        bool seen = false;

        foreach (T t in enumerable)
        {
            if (t.Equals(item))
            {
                if (seen) return true;
                else seen = true;
            }
        }

        return false;
    }
}

You use it like this:

bool multiple = email.ContainsMultiple('@');

This solution also suffers from some degree of inflexibility (the only way to check multiple rules is to implement multiple loops/queries). However, it's "smart" enough to know that you can stop searching the string once you find a duplicate. It's also reusable.

You could also do: