Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if input in textbox is email

Tags:

c#

winforms

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?

like image 536
Matthijs Avatar asked Dec 02 '22 17:12

Matthijs


2 Answers

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
}
like image 173
Grant Winney Avatar answered Dec 04 '22 07:12

Grant Winney


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; }
}
like image 25
siva.k Avatar answered Dec 04 '22 06:12

siva.k