Skip to main content
 首页 » 编程设计

c#之正则表达式只允许 100 到 999999 之间的数字

2024年01月13日33grandyang

谁能帮助 C# 代码使用正则表达式来验证只接受 100 到 999999 之间数字的文本框

谢谢, 吕。

请您参考如下方法:

你不需要正则表达式。

int n; 
if (!int.TryParse(textBox.Text.Trim(), out n) || n<100 || n>999999) 
{ 
  // Display error message: Out of range or not a number 
} 

编辑:如果以 CF 为目标,则不能使用 int.TryParse()。转而使用 int.Parse() 并键入更多错误捕获代码:

int n; 
try 
{ 
  int n = int.Parse(textBox.Text.Trim()); 
  if (n<100 || n>999999) 
  { 
    // Display error message: Out of range 
  } 
  else 
  { 
    // OK 
  } 
} 
catch(Exception ex) 
{ 
   // Display error message: Not a number.  
   //   You may want to catch the individual exception types  
   //   for more info about the error 
}