1

I am trying to make an app where you can add phone numbers and other stuff and I want to check if the number is in correct format so i have been using this loop to check this

int numer = int.Parse(Console.ReadLine());
int count = 0;
int number = numer;

while (number > 0)
{
    number /= 10;
    count++;

    if (number)
    {
        Console.WriteLine(count);
        stringList.Add(nazwa);
        intList.Add(numer);
        //Console.Clear();
        Console.WriteLine($"You added new contact {nazwa} which number is {numer} ");
        Console.WriteLine();
        

    }
    else
    {
        Console.WriteLine(count);
        //Console.Clear();
         Console.WriteLine("This number is in a wrong format!");
         Console.WriteLine();

    }
}

The problem is when i will type number that has 10 digits program will add this number to the database and after that is going to send error to the user.

Rand Random
  • 7,300
  • 10
  • 40
  • 88
  • Research the limits of an int in C# – nicomp Feb 04 '22 at 15:14
  • 1
    Also, phone numbers may not consist of digits only, and leading zeros are significant. So representing a phone number as an integer will not work. – Klaus Gütter Feb 04 '22 at 15:16
  • does your code even compile with `if (number)` as number is a int? - I would do this: `Console.ReadLine().Count(x => char.IsDigit(x));` – Rand Random Feb 04 '22 at 15:17
  • @KlausGütter - the code doesn't really feel like it need to be bullet proof, has homework vibes, so maybe int is enough – Rand Random Feb 04 '22 at 15:18
  • You should look to using Regex for validating phone numbers –  Feb 04 '22 at 15:27
  • That `if` *inside* the `while` loop seems strange - you will get a reaction on *every* iteration of the loop – Hans Kesting Feb 04 '22 at 16:18
  • OT instead of two parallel lists (stringList and intList), create a class that holds both name and phonenumber. Then have a single list for this. – Hans Kesting Feb 04 '22 at 16:20

1 Answers1

2

To validate it you just need:

string input = Console.ReadLine();
bool valid = input.Length == 10 && input.All(char.IsDigit);

I just saw that you want to validate phone-numbers. Well, then this is not sufficient. But if a phone number is valid depends on the country/region. Search for phone number regex(for example in US).

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939