I have the following method and it works correctly as far as handling a real invalid/valid date, however, if I encounter an empty string or a date with a mask such as __/__/____
, I want to pass those as valid, but DateTime.TryParse
invalidates them. How can I modify the method below to pass my Invalid scenarios? Below the following method is an example program:
public bool ValidateDate(string date, out string message)
{
bool success = true;
message = string.Empty;
DateTime dateTime;
if(DateTime.TryParse(date,out dateTime))
{
success = false;
message = "Date is Invalid";
}
return success;
}
void Main()
{
//The only date below that should return false is date4.
string date = "01/01/2020";
string date2 = "";
string date3 = "__/__/____";
string date4 = "44/__/2013";
string message;
ValidateDate(date, out message); //Should return true
ValidateDate(date2, out message); //Should return true
ValidateDate(date3, out message); //Should return true
ValidateDate(date4, out message); //Should return false
}
I can't change it to if(!DateTime.TryParse(date3,out dateTime))
because this will then return false for the dates I want validated.
I also tried doing something like if(!date3.contains("_") && DateTime.TryParse(date3,out dateTime))
, but this still fails. Should I flip the order of my validation? The problem is that I am not just returning false on the first invalid date, I am building a StringBuilder
of all the invalid dates and then returning that, so I didn't think:
if(DateTime.TryParse(date3,out dateTime))
return true;
else
return true;
public bool ValidateDate(string date, out string message)
{
string[] overrides = {"","__/__/____"};
bool success = true;
message = string.Empty;
DateTime dateTime;
if(!overrides.Contains(date) && !DateTime.TryParse(date,out dateTime))
{
success = false;
message = "Date is Invalid";
}
return success;
}