How can I check dates in Perl CGI-script?
I am creating a small reporting script in Perl CGI. I want to have a start / end date to filter events in a report. So now I am wondering how to check entry into some simple Perl path.
The way to generate a form with these fields:
print textfield({-name=>'start_date', -value=>$start_date});
print textfield({-name=>'end_date', -value=>$end_date});
Then it goes to query the database.
Is there an easy Perl-ish way to check these dates? Not only as the correct number of characters, as it is easy enough with a regex, but I would like to report some error if the user enters 02/29/1999 or so.
source to share
I'll just go and be crazy, but I like to use Time :: Local and flip the time back to the time of the epoch, and then when it's a pure pure integer, you can overlay any kind of sanity check you like on it.
source to share
For general form validation, you should use a good structure like D ata :: FormValidator which has a Data :: FormValidator :: Constraints :: DateTime module for date validation
Disclosure: I am the author of Data :: FormValidator :: Constraints :: DateTime
source to share
You can calculate dates in Perl with Time :: Local , which can be set to accept invalid times and still calculate the correct date (like the 32nd day of the month), or check dates and reject invalid dates.
source to share
I almost always prefer to convert something like this to a DateTime object . And I use something like DateTimeX :: Easy to make the process easier:
use DateTimeX::Easy;
my $start_date = DateTimeX::Easy->new( '30th Oct 2009' );
my $from_date = DateTimeX::Easy->new( 'today' );
say $start_date->dmy;
say $from_date->dmy;
# => 30-10-2009
# => 01-10-2009
The only caveat is that DateTime , and its associated modules, are a little useful in memory, which you might want to keep when using in CGI.
/ I3az /
source to share