-1

I need a regular expression to allow only alpahnumric, but not only alpha-strings. E.g. only number 8977 should be denied.

private void txtCompanyName_Validated(object sender, EventArgs e) {
    if(!System.Text.RegularExpressions.Regex.IsMatch(txtCompanyName.Text, @"^[0-9A-Za-z ]+$")) {
        MessageBox.Show("This accepts only alphabetical characters And Numbers");
        txtCompanyName.Focus();
    }
}
dhh
  • 4,289
  • 8
  • 42
  • 59

1 Answers1

1

If I understand correctly, you want the regular expression to accept any string that:

  1. Contains only alphanumeric characters.
  2. Contains at least one letter.

How about this?

@"^[0-9A-Za-z]*[A-Za-z]+[0-9A-Za-z]*$"

Explanation:

  1. Any number of alphanumeric characters, followed by
  2. At least one letter, followed by
  3. Any number of alphanumeric characters.

Your original regular expression also allowed spaces. If this was intentional, just add the space back to the character class used in my code.

user94559
  • 59,196
  • 6
  • 103
  • 103