验证NotePad新行和电子邮件

时间:2017-11-02 13:23:53

标签: c# asp.net

我需要验证电子邮件地址(正确的电子邮件格式)以及每行不包括逗号(,)分号(;),<记事本中的strong>空格(“”)。所以我做了以下似乎没有相应的工作:

StreamReader file = new StreamReader(@"" + email + "");
string line = file.ReadLine(); 

if ((line == null || line.Contains(";") || line.Contains(",") || line.Contains(" ") || line.Contains(email) != IsValidEmail(email)))
{
   return "Check your file. Invalid format!";
}

public bool IsValidEmail(string email)
{
    try
    {
       MailAddress emailAddress = new MailAddress(email);
       return true;
    }
    catch
    {
       return false;
    }
}

上面的代码不会验证电子邮件地址,但它会验证以下内容我的意思是第一行:

at-2017@yahoo.com; we@yahoo.com //Invalid format
at-2018@yahoo.com

但如果分号位于下一行并将其保存到数据库表中,则无法验证:

at-2017@yahoo.com
at-2018@yahoo.com;//Doesn't validate

这很简单,但可能是我做错了,我想弄清楚。任何建议将不胜感激。

3 个答案:

答案 0 :(得分:1)

这样的事情?

void Main()
{
    var file = @"at-2017@yahoo.com;
we@yahoo.com
at-2018@yahoo.com
at-2017@yahoo.com
at-2018@yahoo.com;";

    using (var memory = new MemoryStream(Encoding.UTF8.GetBytes(file)))
    using (var reader = new StreamReader(memory))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            var email = new StringBuilder(line)
                .Replace(";", string.Empty)
                .Replace(",", string.Empty)
                .Replace(" ", string.Empty)
                .ToString();
            var isEmailValid = IsValidEmail(email);
            Console.WriteLine($"{isEmailValid,-5}: {email,-20} original: {line}");
        }
    }
}

bool IsValidEmail(string strIn)
{
    // Return true if strIn is in valid e-mail format.
    return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); 
}

结果:

True : at-2017@yahoo.com    original: at-2017@yahoo.com;
True : we@yahoo.com         original: we@yahoo.com
True : at-2018@yahoo.com    original: at-2018@yahoo.com
True : at-2017@yahoo.com    original: at-2017@yahoo.com
True : at-2018@yahoo.com    original: at-2018@yahoo.com;

答案 1 :(得分:1)

更改if条件,如下所示:

if ((line == null || line.Contains(";") || line.Contains(",") || line.Contains(" ") || !IsValidEmail(line)))

答案 2 :(得分:1)

看起来好像只是从文件中读取第一行数据。试试这个:

foreach (string line in File.ReadLines(@"path to file"))
{
    //do validation for each line
    if (IsValidEmail(line) //etc)
    {
        // do something once line is valid.
    }
}

如果编码是一个问题,则此方法存在重载,您可以指定它:

File.ReadLines() MSDN