C# email regex with no space or ! character allowed

so i have this piece of code and what i need help with is:

i need it to not allow spaces (eg user 123@hotmail.com = invalid)

i need it to allow all characters except the ! character.

i need the domain (after . ) that if more than 2 characters long, must be validated by a supplied file which i have here.

the country codes are. AERO, BIZ, COM, COOP, EDU, GOV, INFO, INT, MIL, MUSEUM, NAME, NET, ORG, PRO

current code.

private void validateBtn_Click(object sender, EventArgs e)
{
    Regex email = new Regex(@"[a-zA-Z0-9]{1,20}@[a-zA-Z0-9]{1,20}.[a-zA-Z]{2,3}$");
    if (!email.IsMatch(emailTxt.Text)) 
    {
        validLbl.Text = "Email invalid";
    }
    else
    {
        validLbl.Text = "Email Valid";
    }
}

any help would be awesome! :D i just cant find any resources to help me.


This is a complete and exhaustive regular expression for checking the validity of an email field. I am pretty sure this would suffice for all your validations related to email addresses.

([a-z0-9][-a-z0-9_+.]*[a-z0-9])@([a-z0-9][-a-z0-9.]*[a-z0-9].(aero|AERO|biz|BIZ|com|COM|coop|COOP|edu|EDU|gov|GOV|info|INFO|int|INT|mil|MIL|museum|MUSUEM|name|NAME|net|NET|org|ORG|pro|PRO)|([0-9]{1,3}.{3}[0-9]{1,3}))

If there are any changes in the domain addresses which you need to validate, then you can modify the regex accordingly. In this case, your code should be like this:

private void validateBtn_Click(object sender, EventArgs e)
{
    Regex validEmailExp = new Regex(@"([a-z0-9][-a-z0-9_+.]*[a-z0-9])@([a-z0-9][-a-z0-9.]*[a-z0-9].(aero|AERO|biz|BIZ|com|COM|coop|COOP|edu|EDU|gov|GOV|info|INFO|int|INT|mil|MIL|museum|MUSUEM|name|NAME|net|NET|org|ORG|pro|PRO)|([0-9]{1,3}.{3}[0-9]{1,3}))");
    if (emailExp.IsMatch(emailTxt.Text.Trim()))
    {
        validLbl.Text = emailTxt.Text + " is valid";
    }
    else
    {
        validLbl.Text = emailTxt.Text + " is invalid";
    }
}

Hope this helps!!!


You can't fully validate emails with a regex. At best you can get close. See this thread for a more complete discussion.

链接地址: http://www.djcxy.com/p/92738.html

上一篇: 使用正则表达式验证电子邮件地址。

下一篇: C#电子邮件正则表达式没有空间或! 字符允许