Bool statement in a while loop c#

12,449

Set the nameavalidation = false

bool nameValidation = false;
while (nameValidation == false) {
Console.Write("Enter your name: ");  // Asks for your name
userName = Console.ReadLine();

if (Regex.IsMatch(userName, @"^[a-zA-Z- ]+$"))  // Validates the input containts characters and/or spaces
 {
    nameValidation = true;              
 }
else  // Error message if the input is not valid
 {
    Console.Clear();  // Clear screen
    Console.WriteLine("Please enter a valid name.");
    nameValidation = false;
  }
}
Share:
12,449
Brian Naranjo
Author by

Brian Naranjo

Updated on June 04, 2022

Comments

  • Brian Naranjo
    Brian Naranjo almost 2 years

    For this code, I had a goto start; statement to repeat the section until a valid name was entered, however my teacher does not like the goto so I had to change it.

    Currently this is what i got but I'm not sure why is it not working. To begin with the program wont even start cuz later in the code I use the input userName and it does not recognize it when I use it in the bool statement. For the purpose of testing it I removed the userName line later on and the program opens but skips the bool statement.

    Please help me make this work. thanks

    bool nameValidation = true;
    while (nameValidation == false) {
        Console.Write("Enter your name: ");  // Asks for your name
        userName = Console.ReadLine();
    
        if (Regex.IsMatch(userName, @"^[a-zA-Z- ]+$"))  // Validates the input containts characters and/or spaces
        {
            nameValidation = true;              
        }
        else  // Error message if the input is not valid
        {
            Console.Clear();  // Clear screen
            Console.WriteLine("Please enter a valid name.");
            nameValidation = false;
        }
    }