I am trying to create a program that requires me to put a validation on the user inputs to only accept letters in a given array of 5. So basically if i am the user i am not allowed to input numbers or special characters, and if i do, i would get an error. Can someone help me out with this? I have tried various searches around and i have not been able to find a solution. I appreciate any help that i can get. This is what i have so far.
class Program
{
static void Main(string[] args)
{
char[] arr = new char[5];
//User input
Console.WriteLine("Please Enter 5 Letters only: ");
for (int i = 0; i < arr.Length; i++)
{
arr[i] = Convert.ToChar(Console.ReadLine());
}
//display
for(int i = 0; i<arr.Length; i++)
{
Console.WriteLine("You have entered the following inputs: ");
Console.WriteLine(arrArray[i]);
}
}
}
char[] arr = new char[5];
//User input
Console.WriteLine("Please Enter 5 Letters only: ");
string s = "abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < arr.Length;)
{
string sChar = Console.ReadLine().ToLower();
if (s.Contains(sChar) && sChar.Length == 1)
{
arr[i] = Convert.ToChar(sChar);
i++;
}
else
{
Console.WriteLine("Please enter a character from A-Z");
continue;
}
}
//display
for (int i = 0; i < arr.Length; i++)
{
Console.WriteLine("You have entered the following inputs: ");
Console.WriteLine(arr[i]);
}
I suggest using a Regular Expression(Regex) for that.
For numbers and letters, the correct Regex is:
string numbersLettersRegex = @"^[a-zA-Z0-9\_]+$"
Then, you just check against that Regex:
if (Regex.isMatch(numbersLettersRegex, arr[i]
{
//do stuff
}
else
{
//print error Message
}
pass your string you're trying to validate in to this func:
public bool checkYo(String myString)
{
return Regex.IsMatch(myString, @"^[a-zA-Z]+$");
}
this will check az and AZ.. if you want just az, just get rid of the AZ part from the above function. hope this helps.
Try this
static void Main(string[] args) {
char[] arr = new char[5];
Console.WriteLine("Please Enter 5 Letters only: ");
string inputstring = Console.ReadLine();
if (Regex.IsMatch(inputstring, @"^[a-zA-Z]+$"))
{
arr = inputstring.ToCharArray();
Console.WriteLine("You have entered the following inputs: ");
//display
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i]);
}
Console.ReadLine();
}
else
{
Console.WriteLine("Enter valid inputs and try again");
Console.ReadLine();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.