Reputation: 83
I want to ensure that the user textbox input starts with 71 or 72 and consists of 10 digits. Otherwise give an error message. How can I do this?
I am using Visual Studio 2015.
Upvotes: 0
Views: 513
Reputation: 112
If you have tons of text boxes than below code would work for you.
var boxes = new List<TextBox>
{
textBox1,
textBox2,
textBox3
};
if ((!boxes.Any(x => x.Text.StartsWith("71")) || !boxes.Any(x => x.Text.StartsWith("72"))) && !boxes.Any(x => x.Text.StartsWith("100")))
{
// Code
}
else
{
// Error
}
Upvotes: 0
Reputation:
if ((TextBox.Text().StartsWith("71") || TextBox.Text().StarsWith("72")) && (TextBox.Text().Length == 10))
{
}
else
{
}
Upvotes: 1
Reputation: 7465
How about a regular expression:
(71|72)\d{8}
Basically, it starts with 71 or 72, and follows with 8 numeric digits.
This code will return a boolean if it matches
System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "(71|72)\d{8}")
Reference:
https://msdn.microsoft.com/en-us/library/sdx2bds0(v=vs.110).aspx
Upvotes: 0
Reputation: 537
Well, you didn't really tell us what you've tried or given us any constraints, so I'm going to give a very generic answer:
public class Program
{
public static void Main(string[] args)
{
string myInput = "";
textBox1.Text.Trim();
if(textBox1.Text.Length() == 10)
{
if(textBox1.Text[0] == '7')
{
if(textBox1.Text[1] == '1' || textBox1.Text[1] == '2')
{
myInput == textBox1.Text();
int num = Int32.Parse(myInput);
//num is now an int that is 10 digits and starts with "71" or "72"
}
}
}
else
{
MessageBox.Show("Invalid input", "Invalid Input");
}
}
}
Additionally, you can probably combine all the if-statements into one large statement. That would allow it to interact better with the else-statement.
Upvotes: 1