How to validate a textbox for an email id?

Jan 16 2008 3:57 AM

Sir,
I have a windows application c#. Net2005, which contains a Form with one text box to enter an email id.
I want to give validation for this textbox (ie) the email id should be in the correct format
After typing the email id in the textbox and when you press the enter key, it should pope up a message box telling that “The Email Id you entered is not in the correct format” (if it is not in the correct format)


It should also be taken care that the number of characters before the symbol @ should be between 4 and 30( >=4 and <=30)

 

I am not sure where we can give a validation in windows application for domain names, since so many domain names exist like com, org, co.in, co.uk etc(ie to check whether the entered domain name exists or not)

 

Currently I have a program as follows

 

 

private void button1_Click(object sender, EventArgs e)

 {

      // This would be what the  user has entered

            string emailAddress = textBox1.Text;

 

            // Create a group called username becuase we want to  look    at it further

            // and we are ignoring everything after the @ symbol

            const string pattern = "^(?<username>.+)@(.)+$";

 

            //Test the format and then store results in a Match object

            Match myMatch = Regex.Match(emailAddress, pattern);

            int cnt = myMatch.Groups["username"].Length;

 

            if ((cnt < 4) && (cnt > 30)) // this is the range you want...

            {

                MessageBox.Show("We have a problem here...");

            }

 

            else

            {

                MessageBox.Show("This is good.");

            }

  }

 

I tried with the above  program.

But when I debugged the program, I found that control is not going to the following line.

(ie it is skipping that line and directly going to the else part)

  const string pattern = "^(?<username>.+)@(.)+$";

Because of that, I am getting the message in the else part

 

(ie)   MessageBox.Show ("This is good.");

 

Can you help me  to get the required output either with the above program or with any other alternative?

Thanks and Regards,

-jm

 


Answers (2)