Ainigma100
Ainigma100

Reputation: 71

Can I make a loop if the user doesn't give me string as an input?

For example if I ask the user to give me his name (string) and he writes numbers, symbols or if he press ENTER I want a loop to tell him to write string in order to continue. I made a loop for integers but I don't know how to make for strings

Console.Write("Please enter the name of the student: ");
//here I made the input to turn into Capitals
name = Console.ReadLine().ToUpper(); 

Console.Write("Please enter their student number: ");
// here I set a condition order to continue. First the input must be integer and second it must be positive
while (!int.TryParse(Console.ReadLine(), out id)||id<0)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.Write("The value must be of integer type, try again: ");
    Console.ResetColor();
}

Upvotes: 0

Views: 84

Answers (1)

ZetaRift
ZetaRift

Reputation: 332

Console.Write("Please enter the name of the student: ");
//here I made the input to turn into Capitals
name = Console.ReadLine().ToUpper(); 
if (Regex.IsMatch(name, @"^[a-zA-Z]+$")) { // If letters only
 // Do something
}else{
 Console.WriteLine("Name must contain letters only");
}

Console.Write("Please enter their student number: ");
// here I set a condition order to continue. First the input must be integer and second it must be positive
while (!int.TryParse(Console.ReadLine(), out id)||id<0)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.Write("The value must be of integer type, try again: ");
    Console.ResetColor();
}

This should check for letters only.

Upvotes: 2

Related Questions