2012-11-29 61 views
1

我需要限制C#中我的文本框中允許的位數。限制文本框中的長度和輸入掩碼

我還需要創建驗證,以便它類似於手機號碼,這意味着它必須以07開頭,總共有11位數字。

有什麼建議嗎?

+2

是否使用WPF,WinForms的或HTML:如果你想在某些方法調用(例如,當你點擊接受按鈕),只需輸入這個代碼? – Heather

+0

winforms,visual studio 2012 for c# –

+0

嘗試任何我可以,應該只是驗證字符的限制和驗證的前兩個字符必須以「」開頭,但我不確定如何去做 –

回答

1

您可以使用MaskedTextBox來提供受控輸入值。一個「07」後跟11位掩碼將爲\0\700000000000

0

你沒有任何代碼作爲例子,所以我會輸入我的。

要限制的字符數,你應該輸入此代碼:如果你想在你的textBox文本以「07」開頭的

private bool Validation() 
{ 
    if (textBox.Text.Length != 11) 
    { 
     MessageBox.Show("Text in textBox must have 11 characters", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
     textBox.Focus(); 
     return false; 
    } 
    return true; 
} 

,你應該輸入此代碼:

private bool Validation() 
{ 
    string s = textBox.Text; 
    string s1 = s.Substring(0, 1); // First number in brackets is from wich position you want to cut string, the second number is how many characters you want to cut 
    string s2 = s.Substring(1, 1); 
    if (s1 != "0" || s2 != "7") 
    { 
     MessageBox.Show("Number must begin with 07", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
     textBox.Focus(); 
     return false; 
    } 
    return true; 
} 

你可以用一種方法合併它,你可以在任何你想要的地方調用它。

private void buttonAccept_Click(object sender, EventArgs e) 
{ 
    if (Validation() == false) return; 
} 
+0

第二個「驗證」方法是錯誤的。更不用說,創建兩個包含一個字符的字符串實例都很難讀取,並在堆上創建不必要的對象。我還會考慮是否有一個名爲'Validation'的方法返回一個顯示消息框的布爾值是一個好主意。不覺得很可重用... –

+0

我看到我不小心鍵入&&而不是||,現在它正在工作。我正在使用像這樣的驗證,它正在工作......如果您有其他代碼與我們分享,我會很樂意嘗試。 – Nemanja