2011-08-24 158 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