Email address input validation

Is there any way to make a textbox input validation for email addresses in wpf C#? Regex or validation expression or anything that can help, best with code sample and some instructions


On the text_changed event you could pass the value of the textbox to a helper class.

public static class ValidatorExtensions
{
    public static bool IsValidEmailAddress(this string s)
    {
        Regex regex = new Regex(@"^[w-.]+@([w-]+.)+[w-]{2,4}$");
        return regex.IsMatch(s);
    }
}

Now on the text changed event you can test the input

private void myTextBox_TextChanged(object sender, EventArgs e)
{
   bool result = ValidatorExtensions.IsValidEmailAddress( myTextBox.Text );
}

There are several ways to check if the email address is valid

About System.Net.Mail.MailAddress
About Regex Expression

 static void Main(string[] args)
        {
            var validMail = "validMail@gmail.com";
            var invalidMail = "123";
            Console.WriteLine("IsValidMailAddress1 Test");
            Console.WriteLine(string.Format("Mail Address : {0} . is valid : {1}", validMail, IsValidMailAddress1(validMail)));
            Console.WriteLine(string.Format("Mail Address : {0} . is valid : {1}", invalidMail, IsValidMailAddress1(invalidMail)));

            Console.WriteLine("IsValidMailAddress2 Test");
            Console.WriteLine(string.Format("Mail Address : {0} . is valid : {1}", validMail, IsValidMailAddress2(validMail)));
            Console.WriteLine(string.Format("Mail Address : {0} . is valid : {1}", invalidMail, IsValidMailAddress2(invalidMail)));

        }


        static bool IsValidMailAddress1(string mail)
        {
            try
            {
                System.Net.Mail.MailAddress mailAddress = new System.Net.Mail.MailAddress(mail);

                return true;
            }
            catch
            {
                return false;
            }
        }

        static bool IsValidMailAddress2(string mailAddress)
        {
            return Regex.IsMatch(mailAddress, @"^([w.-]+)@([w-]+)((.(w){2,3})+)$");
        }
链接地址: http://www.djcxy.com/p/92844.html

上一篇: 在C#窗口窗体中,可以如何实现用于电子邮件地址的MaskedTextBox

下一篇: 电子邮件地址输入验证