5

I am trying to validate if the userinput is an email adress (adding a member to database).

The user will enter data in TextBox, when the validating event gets called; I want to check if the input is a valid email adress. So consisting of atleast an @ and a dot(.) in the string.

Is there any way to do this through code, or perhaps with a Mask from the MaskedTextbox?

slugster
  • 49,403
  • 14
  • 95
  • 145
Matthijs
  • 3,162
  • 4
  • 25
  • 46
  • look up a Regex for validation emails, you should be easily able to find those – x4rf41 Jan 14 '14 at 20:57
  • possible duplicate of [email validation in a c# winforms application](http://stackoverflow.com/questions/1199413/email-validation-in-a-c-sharp-winforms-application) – Liam Jan 21 '15 at 09:07

6 Answers6

14

Don't bother with Regex. It's a Bad Idea.

I normally never use exceptions to control flow in the program, but personally, in this instance, I prefer to let the experts who created the MailAddress class do the work for me:

try
{
    var test = new MailAddress("");
}
catch (FormatException ex)
{
    // wrong format for email
}
Community
  • 1
  • 1
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
  • +1 for mentioning the `MailAddress` class. I had completely forgotten about it. – Brian Jan 14 '14 at 21:05
  • 1
    Holy hell that `Regex` is a mess... lol. I am thinking I may have to delete my answer to this question since I _suggested_ using a `Regex` in the first place. – Brian Jan 14 '14 at 21:35
  • I don't know why but this method doesn't work when you enter a mail like this : mail@mail --> this mail is valid using this way but invalid because it doesn't contain a domain. – HinoHara Mar 30 '15 at 18:07
4

Do not use a regular expression, it misses so many cases it's not even funny, and besides smarter people that us have come before to solve this problem.

using System.ComponentModel.DataAnnotations;

public class TestModel{
    [EmailAddress]
    public string Email { get; set; }
}
siva.k
  • 1,344
  • 14
  • 24
  • This should be the top answer. It builds email validation right into the form, rendered with @Html.ValidationMessageFor(m => m.Email) – SeanMC Sep 25 '17 at 19:10
2

Regex for simple email match:

@"\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b"

Regex for RFC 2822 standard email match:

@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
Dimitri
  • 6,923
  • 4
  • 35
  • 49
1

See: How to: Verify that Strings Are in Valid Email Format - MSDN

The Regex you are looking should be:

"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@)) 
(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,24}))$"

(From the same source)

Habib
  • 219,104
  • 29
  • 407
  • 436
1

I recommend you use this way and it's working well for me.

    Regex reg = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
    if (!reg.IsMatch(txtEmail.Text))
    {
        // Email is not valid
    }
Kervin Guzman
  • 131
  • 1
  • 5
  • 1
    Please provide enough details for answering the question... The OP mentioned that the data comes from a `TextBox`, the validation event is called and it should match a string with `atleast an @ and a dot(.)`. How does your code fulfill these requirements and where are your `isValid` and `UserMessage` variables used in order to accomplish the OP's goal? – CPHPython Jan 09 '17 at 16:31
0

I suggest that you use a Regular Expression like:

@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"

To validate the input of your textbox.

Example code:

private void button1_Click(object sender, EventArgs e)
{
   Regex emailRegex = new Regex(@"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?
                                ^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+
                                [a-z0-9](?:[a-z0-9-]*[a-z0-9])?");

   if (emailRegex.IsMatch(textBox1.Text))
   {
      MessageBox.Show(textBox1.Text + "matches the expected format.", "Attention"); 
   }
}

Edit: I found a better, more comprehensive Regex.

Brian
  • 5,069
  • 7
  • 37
  • 47