A simple DateTime.TryParse or DateTime.Parse already says whether date proposed in string
is a valid date already taking into account the different days of each month and leap years:
public bool isValidDate(string value) {
DateTime result;
return DateTime.TryParse(value, out result);
}
Overload:
public bool isValidDate(int dia, int mes, int ano) {
try {
return DateTime.Parse(dia + "/" + mes + "/" + ano) > DateTime.MinValue;
} catch { }
return false;
}
And other variants ...
A try / catch is required for anomalous cases, such as day = 0
or day 32
, which is possible or any exception that may occur.
In the case of TryParse it is not necessary because try / catch is already built into the function.
Tests run successfully:
c.isValidDate(null); // false
c.isValidDate(""); // false
c.isValidDate(" "); // false
c.isValidDate("31/01/2014"); // true
c.isValidDate("28/02/2014"); // true
c.isValidDate("29/02/2012"); // true
c.isValidDate("29/02/2014"); // false
c.isValidDate("-29/02/2014"); // false
c.isValidDate("29/0/2014"); // false
c.isValidDate(31, 01, 2014); // true
c.isValidDate(28, 02, 2014); // true
c.isValidDate(29, 02, 2012); // true
c.isValidDate(29, 02, 2014); // false
c.isValidDate(-1, 02, 2014); // false
c.isValidDate(31, 01, -1); // false
c.isValidDate(15, 0, 2014); // false
c.isValidDate(99, 99, 9999); // false
c.isValidDate(01, 01, 0001); // true