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 = "[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})+)$");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With