TextBox仅接受数字和逗号#Windows窗体

时间:2016-05-18 11:09:23

标签: c# regex winforms

我想限制只接受数字和逗号的文本框。我怎么能做这个按键?

示例:

 1,2,223,222 -->Valid
 1,,22,,33   -->Invalid
 ab,c,d      -->Invalid

1 个答案:

答案 0 :(得分:2)

如果您想验证输入,可以使用正则表达式

  String input = "1,2,223,222";
  String pattern = "^[0-9]+(,[0-9]+)*$";

  Console.Write(Regex.IsMatch(input, pattern) ? "valid" : "invalid");

小测试:

   String[] tests = new String[] {
     "1,2,223,222",
     "1,,22,,33",
     "ab,c,d", 
   };

   var report = tests
     .Select(item => String.Format("{0,-12} --> {1}", 
                                   item, 
                                   Regex.IsMatch(item, pattern) ? "valid" : "invalid"));

   // 1,2,223,222  --> valid
   // 1,,22,,33    --> invalid
   // ab,c,d       --> invalid
   Console.Write(String.Join(Environment.NewLine, report));

如果你想限制输入,请三思而后行:用户输入的正确程序是什么,比如说

  1,2 

有输入限制,它不能自然不言而喻一个

  "1" -> "1," (invalid! System prevents such an input) -> "1,2"

奇怪

  "1" -> "12" -> "1,2"

所以我建议使用 lenient 用户输入控件:

private void myControl_KeyPress(object sender, KeyPressEventArgs e) {
  // temporary invalid inputs like "1," are allowed
  if ((e.KeyChar < 32) || (e.KeyChar >= '0') && (e.KeyChar <= '9') || (e.KeyChar == ','))
    return;

  // only evident errors (like 'A' or '&') are restricted
  e.Handled = true;
}

然后,最后,(在OK点击等)验证。