in reply to date validation module

You can also use core module Time::Local
use Time::Local qw( timelocal ); my $date_str = '2-31-2006'; my ($m, $d, $y) = $date_str =~ /^(\d+)-(\d+)-(\d+)$/ or die("Invalid input format. Use day-month-year.\n"); my $time = eval { timelocal(0, 0, 0, $d, $m-1, $y) } or die("Invalid date: $@\n"); # For Time::Local < 1.04. Perl >= 5.8.0 doesn't need this. (localtime($time))[3] == $d or die("Invalid date\n");

Update: After doing some testing, I've found that Time::Local's checking is pretty dumb (Update2:) in version < 1.04. Specifically, it assumes every month has 31 days. I added a statment — the last one — to the snippet in this node to fix the problem.

As a function:

use Time::Local qw( timelocal ); sub is_valid_date { my ($date_str) = @_; my ($m, $d, $y) = $date_str =~ /^(\d+)-(\d+)-(\d+)$/ or return 0; my $time = eval { timelocal(0, 0, 0, $d, $m-1, $y) } or return 0; # For Time::Local < 1.04. Perl >= 5.8.0 doesn't need this. (localtime($time))[3] == $d or return 0; return 1; } print(is_valid_date('1-31-2006') ? 'valid' : 'invalid', "\n"); print(is_valid_date('1-32-2006') ? 'valid' : 'invalid', "\n"); print(is_valid_date('2-29-2006') ? 'valid' : 'invalid', "\n");

Replies are listed 'Best First'.
Re^2: date validation module
by ysth (Canon) on Jan 30, 2006 at 19:02 UTC
    Update: After doing some testing, I've found that Time::Local's checking is pretty dumb. Specifically, it assumes every month has 31 days. I added a statment — the last one — to the snippet in this node to fix the problem.
    This appears to be fixed in the Time::Local included with 5.8.0 and later.