1

Is there a way to limit free-text when using Console.ReadLine(); to prevent the use of special characters such as / , % ,$ , #. Currently I allow all characters and then use a .Replace("[special character","") to get rid of any.

Here is an example of my code

                Console.ForegroundColor = ConsoleColor.Yellow;
                Console.WriteLine("Please  type-in the " + reqVariables[h] + " of the model  below:");
                Console.ForegroundColor = ConsoleColor.Magenta;
                freeTextSerialNumbers = Console.ReadLine();

1 Answers1

1

You could use Console.ReadKey(true) in a loop and choose to eliminate those characters from the console while echoing others

Something like this

public static string ReadLine()
{
    var builder = new StringBuilder();

    while (true)
    {
        var key = Console.ReadKey(true);

        if (key.Key == ConsoleKey.Enter)
        {
            return builder.ToString();
        }
        else
        {
            switch (key.KeyChar)
            {
                case '%':
                case '$':
                case [...] //add here all unwanted characters
                    break;
                default:
                    builder.Append(key.KeyChar);
                    Console.Write(key.KeyChar);
                    break;
            }
        }
    }
}
Mad hatter
  • 569
  • 2
  • 11