سؤال

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; 
 }
هل كانت مفيدة؟

المحلول 2

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;
            }

نصائح أخرى

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

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

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top