0

Hi i am a beginner c# programmer.

Need help in writing small code program console in inviting the user to enter their phone number without spaces and hyphens (-) Do the validation and if the user has not respected those conditions, display an error message. And create a loop that will re-ask the user to enter same infos to try again.

Console.WriteLine("Please enter your phone no.: \t");
            string n = Console.ReadLine();
            char[] delimiters = new char[] { ' ', '-' };
            string textBox = Convert.ToString(n);
            string[] numtel = textBox.Split(delimiters);
            bool test = false;

3 Answers3

1

You need a while loop:

char[] delimiters = new char[] { ' ', '-' };
string n;
while(true)
{
    Console.WriteLine("Please enter your phone no.: \t");
    n = Console.ReadLine();

    if(n.Length > 0 && !n.Any(delimiters.Contains)) break;
    else Console.WriteLine("Invalid value, try again.");
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
1

Here's a plain solution of your task:

bool isValid = false;

while(!isValid){
  Console.WriteLine("Please enter your phone no.: \t");
  string phone = Console.ReadLine();  
  isValid = !string.isNullOrWhiteSpace(phone) 
            && phone.s.IndexOfAny(new[] { '-', ' ' }) < 0;
  if (!isValid)
     Console.WriteLine("No spaces or '-' allowed");
}

However this is a poor way of validating a phone number. People use '(', '.' and possibly other characters.

Another way is to use a regex, for example:

  isValid = !string.isNullOrWhiteSpace(phone)
             && Regex.IsMatch(phone, @"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}");
Community
  • 1
  • 1
Sten Petrov
  • 10,943
  • 1
  • 41
  • 61
0

Try This:

var compareStrings = new [] { "-", " " };
string phoneNo=string.Empty;
do
{
    Console.WriteLine("enter phone number without spaces and hyphens ");
    phoneNo = Console.ReadLine();
}while(!(compareStrings.Any((c=>phoneNo.Contains(c)))));
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67