-1

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

i need it to not allow spaces (e.g 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.

Alan Moore
  • 73,866
  • 12
  • 100
  • 156
  • A space in an email address can be valid if it's surrounded by quotes. e.g `"first last"@email.com` By the way, here's my take on validating email addresses. The only way to test if an email address is valid and active is by sending an email to that address. With that in mind, I try to err on the side of accepting too much. – Steve Wortham Jun 04 '14 at 15:40

2 Answers2

0

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!!!

Satwik Nadkarny
  • 5,086
  • 2
  • 23
  • 41
0

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

Community
  • 1
  • 1
Brian Reischl
  • 7,216
  • 2
  • 35
  • 46