Date Validation using just a regex
Ananda
created: 2004-07-01 04:53:45
Hello Monks,

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.

Ananda
Re: Date Validation using just a regex
created: 2004-07-01 05:08:14
Ananda, I think you have set yourself an impossible task. For example, some countries write dates with the month first, some with the day first, and some with the year first. If a date was "01/02/03", how could you possibly work out what it means? Secondly, why try to do this in a regex, when there are modules which can do it? CPAN time modules CPAN date modules
Re^2: Date Validation using just a regex
created: 2004-07-01 09:15:11

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.

Re: Date Validation using just a regex
created: 2004-07-01 05:16:19

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!

Re^2: Date Validation using just a regex
created: 2004-07-01 19:18:24
Consider forwarding this node off to Abigail-II for inclusion in Regexp::Common! I'm sure that he'll request that you make it more generic, but I also know that "dates" is on the "to do list" for the module... Zak


----
Zak - the office
Re: Date Validation using just a regex
created: 2004-07-01 11:52:07
If you don't mind an expression regex...

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