简体   繁体   中英

Check the textbox contains any characters and numbers

I wanted to make where the text in the textbox entered by user, have to contains characters followed by numbers. Example: A1001. I already found a solution using the Regex and show an error message box if the textbox not contains characters followed by number, but once I entered the text "A1" in the textbox, the error message box still appear.

Here is the code that I am using:

void button1_Click(object sender, EventArgs e)
        {
            if (!Regex.IsMatch(this.textBox1.Text, @"(a-zA-Z)"))
            {
                SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2);
            }

            else if (!Regex.IsMatch(this.textBox1.Text, @"(0-9)"))
            {
                SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2);
            }
        }

Your answer very much appreciated!

Thank you

Use one regex for the whole expression:

if (!Regex.IsMatch(this.textBox1.Text, @"^[a-zA-z][0-9]+$"))
{
  SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2);
}

This will match for a string having one character followed by one or more digits. If you want to allow more than one character you have to use [a-zA-z]+ .

As I assume that you want to enter only the product code in this field I also added the ^ for start and $ for end of the string.

^[a-zA-Z]+\d+$

Try this.This one regex will validate your conditions.See demo.

http://regex101.com/r/sU3fA2/25

In forms you can also use the MaskedTextbox, use this control and set the Mask property to:

L0000

This way you force the user to enter one letter(L) and 4 numbers(0000). Of course you can customize it the way you want.

For example LLL-000 will give you 3 letters followed by an indent and 3 numbers.

Your question seems like bit confusing. Please try this inside the button click

        if (!Regex.IsMatch(this.MyTextBox.Text, @"[A-C][0-9]{4}"))
        {
            SystemManager.ShowMessageBox("Please enter the characters followed by the numbers for the product code. \nExample: A1001", "Information", 2);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM