电子邮件地址输入验证

有没有办法在wpf C#中的电子邮件地址进行文本框输入验证? 正则表达式或验证表达式或任何可以提供帮助的东西,最好使用代码示例和一些说明


在text_changed事件上,您可以将文本框的值传递给帮助器类。

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

现在在文本更改的事件上,您可以测试输入

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

有几种方法可以检查电子邮件地址是否有效

关于System.Net.Mail.MailAddress
关于正则表达式

 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/92843.html

上一篇: Email address input validation

下一篇: Why can't I reference System.ComponentModel.DataAnnotations?