May 2009
Intermediate to advanced
510 pages
15h
English
You want to validate dates in the traditional formats mm/dd/yy, mm/dd/yyyy, dd/mm/yy, and dd/mm/yyyy. You want to weed out invalid dates, such as February 31st.
Month before day:
DateTime foundDate;
Match matchResult = Regex.Match(SubjectString,
"^(?<month>[0-3]?[0-9])/(?<day>[0-3]?[0-9])/" +
"(?<year>(?:[0-9]{2})?[0-9]{2})$");
if (matchResult.Success) {
int year = int.Parse(matchResult.Groups["year"].Value);
if (year < 50) year += 2000;
else if (year < 100) year += 1900;
try {
foundDate = new DateTime(year,
int.Parse(matchResult.Groups["month"].Value),
int.Parse(matchResult.Groups["day"].Value));
} catch {
// Invalid date
}
}Day before month:
DateTime foundDate;
Match matchResult = Regex.Match(SubjectString,
"^(?<day>[0-3]?[0-9])/(?<month>[0-3]?[0-9])/" +
"(?<year>(?:[0-9]{2})?[0-9]{2})$");
if (matchResult.Success) {
int year = int.Parse(matchResult.Groups["year"].Value);
if (year < 50) year += 2000;
else if (year < 100) year += 1900;
try {
foundDate = new DateTime(year,
int.Parse(matchResult.Groups["month"].Value),
int.Parse(matchResult.Groups["day"].Value));
} catch {
// Invalid date
}
}Month before day:
@daysinmonth = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31); $validdate = 0; if ($subject =~ m!^([0-3]?[0-9])/([0-3]?[0-9])/((?:[0-9]{2})?[0-9]{2})$!) { $month = $1; $day = $2; $year = $3; $year += 2000 if $year < 50; $year += 1900 if $year < 100; if ($month == 2 && $year % 4 == 0 && ($year % 100 != 0 || $year ...Read now
Unlock full access