【问题标题】:How can I check the format of an E-Mail address?如何检查电子邮件地址的格式?
【发布时间】:2021-12-28 12:25:33
【问题描述】:

我正在构建一个电子邮件验证程序。

如何检查我的电子邮件是否在 @ 之前有 3 个字母,在“.”之后是否有 2 个字母我试过else if,但没用。

string rightPassword = "red@gmx.to";
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");

【问题讨论】:

  • 你给Console.ReadLine();打了两次电话。在第二个之后,您不再计算 redtolengthRedlengthTo。这些计算应该在 ReadLine 之后的循环内。第一个 Readline 是多余的。
  • 很少有正则表达式验证是电子邮件地址的正确工具。如果您需要有效电子邮件地址,请向他们发送验证电子邮件。如果他们可以完成电子邮件调用的验证,则该地址是有效的。如果他们不能,那么谁在乎它是否匹配潜在有效的电子邮件地址。

标签: c# validation if-statement


【解决方案1】:

只需使用Regular expressions 进行模式匹配。

您应该使用this 正则表达式来实现您想要的:^\w{3}@\w+.\w{2}$

代码示例:

string email = "abc@aa.co";
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");

【讨论】:

  • 好的,谢谢。我将使用 RedFox 的那个。我不熟悉正则表达式
【解决方案2】:

如果您不想使用正则表达式,即使我们强烈建议您使用它,您也可以添加一个方法:

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

并在您的代码中使用该方法:

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

但请记住,上面的示例不会验证数字或符号。您可以使用email[i].IsSymbol()email[i].IsNumber() 进行检查。


注意: x@com 是域名注册商的有效电子邮件地址。也就是说,他们中的大多数人使用子域作为他们的电子邮件。 x@x.com 例如。处理所有现实世界的电子邮件案例并不像看起来那么简单。

【讨论】:

  • 谢谢 Redwolf,我正在找这个。
【解决方案3】:

使用Char.IsLetter()方法

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

【讨论】:

    【解决方案4】:

    您也可以使用拆分。

    类似

    string red = rightPassword.Split('@')[0];
    string to = rightPassword.Split('.').Last();
    

    如果您使用,您还可以检查“@”后面的内容

    string red = rightPassword.Split('@')[0];
    string gmx= rightPassword.Split('@')[1];
    string to = rightPassword.Split('.').Last();
    

    【讨论】:

      猜你喜欢
      • 2010-11-14
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 2012-04-28
      • 1970-01-01
      • 2020-06-25
      • 2022-07-14
      • 1970-01-01
      相关资源
      最近更新 更多