4

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");
    }
}
2
  • 1
    Looks like your reg exp is wrong. It looks to me like it's saying "allow anything except a-zA-Z0-9." Commented Jun 20, 2011 at 18:21
  • 1
    "I know I'll use Regex to solve my problem!" Now you have two problems. Commented Jun 20, 2011 at 18:22

3 Answers 3

7

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]*$";
Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

5

Probably incorrect regex. Maybe you meant this:

String AllowedChars = @"^[a-zA-Z0-9]*$";

This would allow any number (including none) of alphanumeric chars. I have removed the period (which matches any character) because it does not make much sense in this context.

1 Comment

The period may have been intended to be a literal period character rather than a metacharacter (perhaps "www.example.com" is a valid input), especially considering the variable name of AllowedChars. In that case, it should be included within the square brackets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.