4

How do I ensure that the user of my web form application has entered an email address? I have seen examples using regex and the EmailAddress(), but how can I implement one or the other in the if else statement below?

if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100)
{
    emailErrorString = "Email: Enter email address.  No more than 100 characters.\n\n";
    emailString = null;
    errorMessage = true;
}
else
{
    emailString = emailTextBox.Text;
    emailErrorString = null;
}

I tried the following code and it came back true even when I entered an invalid email address "jj@jj. I did not enter ".com, or ,net, or anything like that:

 if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 ||                                          
      IsValid(emailTextBox.Text).Equals(false)) 
 {
     emailErrorString = "Email: Enter a valid email address. No more than 100
           characters.\n\n"; emailString = null; errorMessage = true; 
 } 
 else 
 { 
      emailString = emailTextBox.Text; emailErrorString = null; 
 }
antman1p
  • 514
  • 2
  • 11
  • 25
  • I'm not sure why I was voted down here. I have done the research and as I said above I have seen the questions and answers pertaining to the use of regex and Emailaddress() validation, but I do not understand how to implement it into my code. If you are going to vote me down for lack of research I would appreciate a link to the answer you suggest exists. Thanks ALOT! – antman1p Mar 04 '14 at 19:16
  • Nothing from [searching](http://stackoverflow.com/search?q=%5Bc%23%5D+validate+email)? – crashmstr Mar 04 '14 at 19:36
  • http://stackoverflow.com/questions/5342375/c-sharp-regex-email-validation That's exactly what you need. – Guillaume Philipp Mar 04 '14 at 19:36
  • Thank you sir! I think I figured out how to implement the MailAddress() in my code! – antman1p Mar 04 '14 at 19:45
  • Yes crashmstr, I did quite a bit of searching, and again I wasn't sure how to implement the MailAddress() into my code. Thank you everyone for all of your help. I am new to programming. – antman1p Mar 04 '14 at 19:50
  • I tried this: if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 || IsValid(emailTextBox.Text).Equals(false)) { emailErrorString = "Email: Enter a valid email address. No more than 100 characters.\n\n"; emailString = null; errorMessage = true; } else { emailString = emailTextBox.Text; emailErrorString = null; } It is returning true when I enter an invalid email address like jj@jj. – antman1p Mar 04 '14 at 20:24

4 Answers4

4

You can make use of MailAddress class, like below:

public bool IsValid(string emailAddress)
{
    try
    {
        MailAddress m = new MailAddress(emailaddress);
        return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

Alternatively, you can use RegEx (you should be able to find one suitable for validating email address). This link gives a basic idea of available characters/patterns: Regexlib

Manish Basantani
  • 16,931
  • 22
  • 71
  • 103
  • Thank you! I think I figured out how Ican implement this in my code. – antman1p Mar 04 '14 at 19:45
  • Would you please raise my question? Thank you again! – antman1p Mar 04 '14 at 19:55
  • I tried this: if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 || IsValid(emailTextBox.Text).Equals(false)) { emailErrorString = "Email: Enter a valid email address. No more than 100 characters.\n\n"; emailString = null; errorMessage = true; } else { emailString = emailTextBox.Text; emailErrorString = null; } It is returning true when I enter an invalid email address like jj@jj – antman1p Mar 04 '14 at 20:53
1

I tried using the MailAddress() example and "jj@jj" came back as a valid email. So, I tried the following and it worked perfectly:

 ///Create a Regular Expression
 Regex regEmail = new Regex(@"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?
      \^_`{|}~]+)*"
        + "@" 
        + @"((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$");

And:

 ///test the email textbox against the created Regular Expression
 if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 || 
                !regEmail.IsMatch(emailTextBox.Text))
            {
                emailErrorString = "Email: Enter a valid email address.  No more than
                     100 characters.\n\n";
                emailString = null;
                errorMessage = true;
            }
            else
            {
                emailString = emailTextBox.Text;
                emailErrorString = null;
            }
antman1p
  • 514
  • 2
  • 11
  • 25
  • "jj@jj" actually _is_ a valid email address, an email address without a TLD is rarely used but still valid. If "jj" is a host known to the email server that tries to send mail, it will deliver the message to the email server running at the host "jj". Since the lack of a TLD usually is a sign of custom host configuration, it would not be interesting to support it for most external-facing applications, but on the intranet of a company this could be useful. – x13 Sep 06 '16 at 19:57
0

Well, if it could be any kind of e-mail adress, and the code doesn't have to check whether it's valid or not, you could use this code, which is based on this structure:

example@domain.extension

The only thing is to check whether the string contains an @ character, a . character, and a valid e-mail domain and extension (com/de/org/...).

public bool CheckAdress(string Adress)
{
    if (Adress.IndexOf('@') == -1)//if there are no @ characters in the Adress
    {
        return false;
    }
    switch (Adress.Substring(Adress.IndexOf('@') + 1, Adress.IndexOf('.') - Adress.IndexOf('@') + 1)//examines the domain between the @ and the. characters
    {
        case "gmail":
        case "freemail":
        case "citromail":
        //... (any valid domain name)
        break;
        default:
        return false;
    }
    switch (Adress.Substring(Adress.IndexOf('.') + 1, Adress.Length - Adress.IndexOf('.') + 1))//finally examines the extension
    {
        case "com":
        case "de":
        case "org":
        //... (any valid extension)
        break;
        default:
        return false;
    }

    //if all of these have not returned false, the adress might be valid, so
    return true;
}

This code only works when there's nothing else in the TextBox, just the adress in question. I know this is a bit long and maybe not the most perfect answer. But this way you can customize, which domains and extensions are accepted by the code, and which are not.

But if you want to check if this e-mail adress exists in reality, I don't think this solution works.

I didn't add the code that throws exception when the length is more than 100, but you can add it anytime.

Hope this helps a bit! :)

Richtenzorg
  • 178
  • 1
  • 1
  • 9
  • 1
    I don't think you can check valid Top Level Domains. There are FAR too many now. Or a valid Domain either for that matter. Pretty much general syntax is the only thing you can do. – Brad Mar 04 '14 at 19:34
  • Thank you for the answer! I'm not so concerned whether it is from any particular domains, or whether the address exists or not, only that it is in the correct format. This would def do the trick, however I know there is a shorter way of doing it using the MailAddress() class, as seen here: http://stackoverflow.com/questions/21123829/check-if-input-in-textbox-is-email . I am just unsure how to implement it into my code/if then statement. – antman1p Mar 04 '14 at 19:37
  • Also, I'd greatly appreciate anyone that would raise my question up. My reputation went down after the drive by dropping. – antman1p Mar 04 '14 at 19:40
0

Try creating a new System.Net.Mail.MailAddress object. Pass in the Text property of the TextBox you are using for user input as the parameter to this constructor. Wrap this in a Try Catch block. You'll get a FormatException if the address is invalid.

Timothy Klenke
  • 814
  • 1
  • 10
  • 21
  • Thank you! Could you please raise my question? – antman1p Mar 04 '14 at 19:55
  • I tried this: if (emailTextBox.Text == "" || emailTextBox.Text.Length > 100 || IsValid(emailTextBox.Text).Equals(false)) { emailErrorString = "Email: Enter a valid email address. No more than 100 characters.\n\n"; emailString = null; errorMessage = true; } else { emailString = emailTextBox.Text; emailErrorString = null; } It is returning true when I enter an invalid email address like jj@jj – antman1p Mar 04 '14 at 20:54