I am trying to achieve date validation in a single regex without any additional test conditions. The validations include:
a)Check date format
b)Check for leap
c)Check for the correct number of days in a month
I have followed various examples but have not acheived the desired result.
Thanks in advance for all the help extended.
Difficult yes, unwise perhaps, but not impossible.
If presented with 01/02/03, with absolutely no context, then you would be correct, but that is rarely the case. All it takes is a few heuristics to be able to make sense of that date.
Why on earth ... ? Well, why not ...
/(?=\d{4}-\d\d-\d\d) # Date format
(?=.{8}(?:0[1-9]|[12]\d|3[01])) # Day 01-31
(?=.{5}(?:0[1-9]|1[0-2])) # Month 01-12
(?!.{5}(?:0[2469]|11)-31) # Not 31 days in those months
(?!.{5}02-30) # Never 30 days in Feb
(?!...[13579]-02-29) # Not a leap year
(?!..[13579][048]-02-29) # -"-
(?!..[02468][26]-02-29) # -"-
(?!.[13579]00-02-29) # -"-
(?![13579][048]00-02-29) # -"-
(?![02468][26]00-02-29) # -"-
/x
print "Just another Perl ${\(trickster and hacker)},"
The Sidhekin proves Sidhe did it!
while(<>){
chomp;
$_ = 'Use YYYY-MM-DD format' unless s/^(\d{4})-(\d\d)-(\d\d)$/
$1<1 || $2<1 || $3<1 ? 'Year, month, and day must be greater than 0' :
$2>12 ? 'Month must be less than 13' :
$3>31 ? 'Day must be less than 32' :
$3==30&&$2==2 ? 'February has less than 30 days' :
$3==29 && $2==2 && $1%4!=0 ? 'February only has 29 days in a leap year' :
$3==31 && $2 =~ m!0[2469]|11! ? '30 days hath September, yada yada..' : $_ /e;
print ": $_ :\n";
}
perlmonks.org content © perlmonks.org and Ananda, beable, delirium, pbeckingham, Sidhekin, zakzebrowski
prlmnks.org © 2006 edmund von der burg (eccles & toad)
v 0.03