0

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.

Beyza S.
  • 83
  • 3
  • 4
    Post what you've tried so far. – dcg Jul 09 '18 at 13:08
  • 1
    This [question/answer](https://stackoverflow.com/questions/8915151/c-sharp-validating-input-for-textbox-on-winforms) will give you a starting point – JayV Jul 09 '18 at 13:09

4 Answers4

1

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.

Tom Hood
  • 497
  • 7
  • 16
1
 if ((TextBox.Text().StartsWith("71") || TextBox.Text().StarsWith("72")) && (TextBox.Text().Length == 10))
 {

 }
 else
 {


 }
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/20247704) – H. Pauwelyn Jul 09 '18 at 15:47
  • didn't need clarification, it's exactly what he asked for. –  Jul 09 '18 at 16:02
  • 1. He asked for 10 digets. 2. Add comment when the condition is true or false in human readable text. – H. Pauwelyn Jul 09 '18 at 16:35
0

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
Ctznkane525
  • 7,297
  • 3
  • 16
  • 40
0

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
    }
Nandu
  • 103
  • 9