2012-11-29 69 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