如何保证winform文本框输入以特定数字开头?

How to ensure that winform text box input starts with a specific number?

我想确保用户文本框输入以 71 或 72 开头并由 10 位数字组成。否则给出错误信息。我该怎么做?

我正在使用 Visual Studio 2015.

好吧,你并没有真正告诉我们你尝试了什么,也没有给我们任何限制,所以我将给出一个非常笼统的答案:

public class Program
    {
        public static void Main(string[] args)
        {
            string myInput = "";
            textBox1.Text.Trim();
            if(textBox1.Text.Length() == 10)
            {
                if(textBox1.Text[0] == '7')
                {
                    if(textBox1.Text[1] == '1' || textBox1.Text[1] == '2')
                    {
                        myInput == textBox1.Text();
                        int num = Int32.Parse(myInput);
                        //num is now an int that is 10 digits and starts with "71" or "72"
                    }
                }
            }
            else
            {
               MessageBox.Show("Invalid input", "Invalid Input");
            }          
        }
    }

此外,您或许可以将所有 if 语句组合成一个大语句。这将使它能够更好地与 else 语句交互。

正则表达式怎么样:

(71|72)\d{8}

基本上是71或72开头,后面是8位数字

如果匹配

,此代码将return一个布尔值
System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "(71|72)\d{8}")

参考:

https://msdn.microsoft.com/en-us/library/sdx2bds0(v=vs.110).aspx
 if ((TextBox.Text().StartsWith("71") || TextBox.Text().StarsWith("72")) && (TextBox.Text().Length == 10))
 {

 }
 else
 {


 }

如果您有大量的文本框,下面的代码将适合您。

        var boxes = new List<TextBox>
    {
         textBox1,
         textBox2,
         textBox3
    };

    if ((!boxes.Any(x => x.Text.StartsWith("71")) || !boxes.Any(x => x.Text.StartsWith("72"))) && !boxes.Any(x => x.Text.StartsWith("100")))
    {
        // Code
    }
    else
    {
        // Error
    }