I have a class that is an entity from a database that has a bunch of dates represented as strings. For example, it could be something like this:
public class Stuff
{
public string Date1 {get;set;}
public string Date2 {get;set;}
public string Date3 {get;set;}
public string Date4 {get;set;}
}
I then have a Validation method that validates other properties and also validates the date properties. Currently, I am validating each date separately for each object. This works, but I was wondering if there was a way I could make it generic so I didn't have to duplicate code across classes and within the class itself. I am currently doing something like:
public bool ValidateDate(string date)
{
string[] overrides = {"","__/__/____"};
bool success = true;
DateTime dateTime;
if(!overrides.Contains(date) && !DateTime.TryParse(date,out dateTime))
{
success = false;
}
return success;
}
//Notice in this method I am repeating the if statements.
public bool Validate(Stuff stuff, out string message)
{
message = string.Empty;
bool success = true;
if(!ValidateDate(stuff.Date1))
{
success = false;
message = "Date 1 is invalid";
}
if(!ValidateDate(stuff.Date2))
{
success = false;
message = "Date 2 is invalid";
}
if(!ValidateDate(stuff.Date3))
{
success = false;
message = "Date 3 is invalid";
}
if(!ValidateDate(stuff.Date4))
{
success = false;
message = "Date 4 is invalid";
}
return success;
}
void Main()
{
string message;
Stuff stuff = new Stuff();
stuff.Date1 = "01/01/2020";
stuff.Date2 = "__/__/____";
stuff.Date3 = "";
stuff.Date4 = "44/__/____";
bool valid = Validate(stuff, out message);
}
I thought about doing something like:
public bool Validate<T>(T value, out string message)
{
//Validation here
}
But, correct me if I am wrong, but this would require that I get the properties and use reflection to check the value of the date and my other problem with this is that the properties are strings, so there is no way for me to check if it is a DateTime?