2011-08-24 162 views
1

之间只有数字任何人都可以使用正则表达式来验证它仅接受数字感谢100和999999 正则表达式允许100和999999

之间

,一个文本框 吕C#代码帮助。

+0

将数字以一个或多个零开始(例如00222)是否有效输入? – Jon

+3

您使用哪种UI技术?其中一些允许在他们的模型上使用Range属性并自动验证。 –

回答

3

您的要求转换为三至六位数字,首先不是零。我不记得C#是否默认了RE,所以我也把它们放入了。

^[1-9][0-9]{2,5}$
+1

用RE以外的东西来表达这个要好得多。 –

+0

我知道这不处理前导零。对于那些用户不是程序员的用户输入,禁止前导零是正确的做法。 –

+0

C#不会固定它们 –

10

你不需要这个正则表达式。

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 
} 
+1

是否允许前导零?否则,此解决方案不完整。 – mob

+2

@mob:我是用户头脑。当我被要求验证用户输入时,我不会拒绝0100.用户会回复_Stupid @#$ computer_。她会是对的! –

+0

@serge我不能使用int.TryParse(),因为我在Windows Mobile CF应用程序中使用它。 – siva

1

一个简单的方法是使用正则表达式

^[1-9][0-9]{2,5}$ 

如果你想允许前导零(但仍保持6 - 数位限制)的正则表达式将是

^(?=[0-9]{3,6}$)0*[1-9][0-9]{2,5} 

这最后一个可能值得一些解释:首先使用正向前查找[(?=)]以确保整个输入是3到6位数字,然后确保它由任意数量的前导零组成,后面跟着100-999999范围内的一个数字。

但是,它可能是一个更好的主意,使用更适合任务的东西(也许数字比较?)。

+1

'001'无效 – soniiic

+0

@soniiic:对不起,你能解释一下吗? – Jon

+0

@Jon,你的第二个表达式无效。你想要更类似'^ 0 * [1-9] \ d {2,5} \ z' – Qtax

1

你必须使用正则表达式吗?如何

int result; 
if(Int.TryParse(string, out result) && result > 100 && result < 999999) { 
    //do whatever with result 
} 
else 
{ 
    //invalid input 
} 
+0

布赖恩,我不能使用int.TryParse(),因为我在Windows Mobile CF应用程序中使用它。 – siva

0

另一种方法,你可以考虑

[1-9]\d{2,5}

0

为什么不使用NumericUpDown控制,而不是它可以让你specifiy最小和最大的价值? 而且只会让数字太大,为您节省更多的验证,以确保任何非数字可以输入

从例如:

public void InstantiateMyNumericUpDown() 
{ 
    // Create and initialize a NumericUpDown control. 
    numericUpDown1 = new NumericUpDown(); 

    // Dock the control to the top of the form. 
    numericUpDown1.Dock = System.Windows.Forms.DockStyle.Top; 

    // Set the Minimum, Maximum, and initial Value. 
    numericUpDown1.Value = 100; 
    numericUpDown1.Maximum = 999999; 
    numericUpDown1.Minimum = 100; 

    // Add the NumericUpDown to the Form. 
    Controls.Add(numericUpDown1); 
} 
0

也许接受前导零:

^0*[1-9]\d{2,5}$ 
+0

我也可以推荐http://gskinner.com/RegExr/来轻松测试正则表达式:s。 – erikH