Reputation: 11
I need to limit the number of digits allowed in my TextBox in C#.
I also need to create the validation so that it will resemble a mobile number, meaning it must begin with 07 and have a total of 11 digits.
Any suggestions?
Upvotes: 1
Views: 7913
Reputation: 814
You don't have any code as example, so, I would type mine.
To limit the number of characters you should type this code:
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;
}
If you want that text in your textBox begin with "07", you should type this code:
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;
}
You can merge this in one method ofcource, and you can call it where ever you want. If you want to call in some method(for example when you click on accept button) just type this code:
private void buttonAccept_Click(object sender, EventArgs e)
{
if (Validation() == false) return;
}
Upvotes: 0
Reputation: 14507
You can use a MaskedTextBox to provide a controlled input value. A "07" followed by 11 digit mask would be \0\700000000000
.
Upvotes: 1