Last active
April 5, 2022 20:26
-
-
Save manavm1990/9c06d7c075d39518aab3b8434dd64cf1 to your computer and use it in GitHub Desktop.
Demo methods to share with student for validating stuff from Console
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class ConsoleIo | |
{ | |
internal static string PromptRequired(string message) | |
{ | |
var res = PromptUser(message); | |
while (string.IsNullOrEmpty(res)) | |
{ | |
View.DisplayHeader("Input required❗"); | |
res = PromptUser(message); | |
} | |
return res; | |
} | |
internal static decimal PromptUser4Num(string message) | |
{ | |
decimal result; | |
while (!decimal.TryParse(PromptUser(message), out result)) | |
{ | |
PromptUser("Invalid Input. Press Enter to Continue"); | |
} | |
return result; | |
} | |
internal static decimal PromptUser4Num(string message, decimal? min, decimal? max) | |
{ | |
decimal result; | |
while (!decimal.TryParse(PromptUser(message), out result) || result < min || result > max) | |
{ | |
View.Prompt2Continue(GetErrorMessage(min, max)); | |
} | |
return result; | |
} | |
internal static DateOnly PromptUser4Date(string message, DateOnly? min, DateOnly? max) | |
{ | |
DateOnly result; | |
while (!(DateOnly.TryParse(PromptUser(message), out result)) || (result < min) || (result > max)) | |
{ | |
View.Prompt2Continue(GetErrorMessage(min, max)); | |
} | |
return result; | |
} | |
private static string GetErrorMessage<T>(T? min, T? max) | |
{ | |
string? errorMessage = null; | |
if (min != null) errorMessage += $"Invalid Input. Must be after {min.ToString()}❗"; | |
if (max != null) errorMessage += $"Invalid Input. Must be before {max.ToString()}❗"; | |
errorMessage ??= "Invalid Input. Press Enter to Continue❗"; | |
return errorMessage; | |
} | |
private static string PromptUser(string message) | |
{ | |
Console.Write(message); | |
return Console.ReadLine() ?? string.Empty; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
static class View | |
{ | |
internal static void DisplayHeader(string header) | |
{ | |
Console.WriteLine(header); | |
Console.WriteLine("".PadLeft(header.Length, '=')); | |
} | |
internal static void Prompt2Continue(string message = "Press any key to continue...") | |
{ | |
DisplayHeader(message); | |
Console.ReadLine(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment