Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Using regex with if statements

I have some code that checks a fields input against a regex, although for some reason (no matter what I put in the field, it returns flase. Is there something I have missed?

private void textBox5_Validating(object sender, CancelEventArgs e)
{
    String AllowedChars = @"^a-zA-Z0-9.$";
    if (Regex.IsMatch(textBox5.Text, AllowedChars))
    {
        MessageBox.Show("Valid");
    }
    else
    {
        MessageBox.Show("Invalid");
    }
}
like image 972
Dan Avatar asked Dec 03 '22 02:12

Dan


2 Answers

The regex makes no sense to me. This one would (notice the square brackets used for defining an alphabet):

String AllowedChars = @"^[a-zA-Z0-9]*$";
like image 165
naivists Avatar answered Dec 14 '22 02:12

naivists


What you want is to group those characters and allow 0 or more:

@"^[a-zA-Z0-9.]*$"

Otherwise, what you posted allows "a-zA-Z0-9" and one more character only.

like image 24
Ed Chapel Avatar answered Dec 14 '22 00:12

Ed Chapel