Search code examples
c#datetryparse

Check if user input is a valid date


I am building a calendar and I want to check if the user input is a valid date. I got this far and now I dont' know how to repeat the message "invalid date" until it's a valid one.


My code:

var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"};

Console.Write("\nSet your date: ");

string readAddMeeting = Console.ReadLine();
DateTime scheduleDate;

bool validDate = DateTime.TryParseExact(
    readAddMeeting,
    dateFormats,
    DateTimeFormatInfo.InvariantInfo,
    DateTimeStyles.None,
    out scheduleDate);

if (validDate)
{
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("Valid date");
    Console.ForegroundColor = ConsoleColor.White;
}
else
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("Invalid date: \"{0}\"", readAddMeeting);
    Console.ForegroundColor = ConsoleColor.White;
}

Solution

  • try something like:

    var dateFormats = new[] {"dd.MM.yyyy", "dd-MM-yyyy", "dd/MM/yyyy"};
    
    bool validate = true;
    while (validate) // Loop indefinitely
    {
        Console.Write("\nSet your date: "); // Prompt
        string readAddMeeting = Console.ReadLine(); // Get string from user
    
        DateTime scheduleDate;
        if(DateTime.TryParseExact(readAddMeeting,dateFormats, DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None, out scheduleDate))
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Valid date");
            validate = false;
        }
        else
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("Invalid date: \"{0}\"", readAddMeeting);
        }
        Console.ForegroundColor = ConsoleColor.White;
    }