You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现符合字符与顺序规则的用户输入(邮箱)验证?

邮箱输入验证实现方案

核心问题拆解

先明确几个关键信息:

  • 你需要的邮箱规则:仅包含字母、数字、@、-、_,且符合标准邮箱结构(必须有且仅有一个@,@前后都要有合法内容)
  • .NET 没有像DateTime那样的内置邮箱值类型,但有现成的验证工具,也可以自定义规则实现

具体实现方法

方法1:用.NET内置MailAddress类验证(推荐)

这是最省心的方式,.NET已经封装了成熟的邮箱格式校验逻辑,还能额外满足你对字符范围的限制:

public string GetValidEmail()
{
    string input;
    while (true)
    {
        Console.WriteLine("Enter Email");
        input = Console.ReadLine();
        
        if (string.IsNullOrEmpty(input))
        {
            Console.WriteLine("Email was not valid");
            continue;
        }

        try
        {
            // 尝试创建MailAddress对象,格式不合法会抛出异常
            var mailAddress = new System.Net.Mail.MailAddress(input);
            // 额外检查所有字符是否在允许范围内
            if (input.All(c => char.IsLetterOrDigit(c) || c == '@' || c == '-' || c == '_'))
            {
                return input;
            }
            else
            {
                Console.WriteLine("Email contains invalid characters. Only letters, digits, @, -, _ are allowed.");
            }
        }
        catch (FormatException)
        {
            Console.WriteLine("Email was not valid");
        }
    }
}

方法2:自定义正则表达式验证

如果需要更精细的规则控制,可以用正则表达式精准匹配:

using System.Text.RegularExpressions;

public string GetValidEmail()
{
    string input;
    // 正则规则:仅允许指定字符,且符合邮箱基本结构(@前后有内容、带域名后缀)
    var emailRegex = new Regex(@"^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+\.[a-zA-Z]+$");
    
    while (true)
    {
        Console.WriteLine("Enter Email");
        input = Console.ReadLine();
        
        if (string.IsNullOrEmpty(input))
        {
            Console.WriteLine("Email was not valid");
        }
        else if (!emailRegex.IsMatch(input))
        {
            Console.WriteLine("Email was not valid");
        }
        else
        {
            return input;
        }
    }
}

正则表达式说明:

  • ^[a-zA-Z0-9_-]+:字符串开头必须是至少一个允许的字符(字母、数字、-、_)
  • @:必须包含且仅包含一个@
  • [a-zA-Z0-9_-]+:@后必须有至少一个允许的字符
  • \.[a-zA-Z]+$:必须带域名后缀(比如.com、.cn),结尾是字母

你的疑问解答

  • if语句是否适用:完全适用,你现有代码的结构没问题,只需要把condition替换成上面的验证逻辑(比如!emailRegex.IsMatch(input)或者异常捕获后的判断)
  • 有没有类似DateTime的类型:.NET没有专门的邮箱值类型,但MailAddress类可以看作是邮箱的封装类,它内部会自动处理格式校验,和DateTime处理日期的逻辑类似
  • OOP相关建议:如果后续要复用验证逻辑,可以把校验逻辑封装成单独的工具类,符合OOP的封装原则:
public static class EmailValidator
{
    public static bool IsValid(string email)
    {
        if (string.IsNullOrEmpty(email))
            return false;
        
        try
        {
            var mailAddress = new System.Net.Mail.MailAddress(email);
            return email.All(c => char.IsLetterOrDigit(c) || c == '@' || c == '-' || c == '_');
        }
        catch
        {
            return false;
        }
    }
}

之后在循环里直接用else if (!EmailValidator.IsValid(input))即可,代码更清晰也方便复用。

内容的提问来源于stack exchange,提问作者elizac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 04:20:27