Home > OS >  How can I check the format of an E-Mail address?
How can I check the format of an E-Mail address?

Time:12-28

I am building an e-mail validation program.

How can I check if my E-Mail has 3 letters before the @ and 2 letters after the "." I tried else if but it didn't work.

string rightPassword = "[email protected]";
string enter = Console.ReadLine();

string red = rightPassword.Substring(0, 3);
string to = rightPassword.Substring(8);

int lengthRed = red.Length;
int lengthTo = to.Length;
do
{
    Console.Write("Write the E-Mail: ");
    enter = Console.ReadLine();

    if (rightPassword == enter)
    {
        Console.WriteLine("Right Password");
    }
    else if (lengthRed < 3 ) // I have to check if it has 3 letters before the @//
    {

      Console.WriteLine("You need 3 letters before the @")
    }
    else if (lengthTo < 2)
    {
         Console.WriteLine("You need 2 letter after the ".")     
    }
} while (enter != "enter");

CodePudding user response:

Just use explanation

code example:

string email = "[email protected]";
Regex regex = new Regex(@"^\w{3}@\w .\w{2}$");
Match match = regex.Match(email);
if(match.Success)
    Console.WriteLine("Email matches pattern");
else Console.WriteLine("Email does not matches pattern");

CodePudding user response:

If you don't want to use Regular Expressions, even though it is highly encouraged, you can add a method:

public static bool HasValidUsername(string email)
{
    for (int i = 0; i < 3; i  )
    {
        if (!email[i].IsLetter())
        {
            return false;
        }
    }
    return true;
}

And use the method in your code:

else if (!HasValidUsername(enter))
{
    Console.WriteLine("You need 3 letters before the @");
}

But keep in mind, that the example above will not validate numbers or symbols. You could use email[i].IsSymbol() or email[i].IsNumber() to check for that.


Note: x@com is a valid email adress for a domain registrar. That said, most of them use a subdomain for their email. [email protected] for example. Handling all real world email cases is not as trivial as it might seem.

CodePudding user response:

Using Char.IsLetter() method

public bool IsValidEmail(string email)
{
    return email.Length > 2 Char.IsLetter(str[0]) && Char.IsLetter(str[1]) && Char.IsLetter(str[2]);
}
  • Related