Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Email address input validation

Tags:

c#

wpf

textbox

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

like image 570
Tinaira Avatar asked Nov 29 '22 14:11

Tinaira


2 Answers

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 );
}
like image 85
Justin Avatar answered Dec 11 '22 10:12

Justin


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 = "[email protected]";
            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})+)$");
        }
like image 20
Fatih Sert Avatar answered Dec 11 '22 08:12

Fatih Sert