views:

131

answers:

5

I'm creating a small reporting script in Perl CGI. I want to have the start/end date there to filter the events on the report. So now I wonder how to validate the input in some easy, Perl-way.

The way I generate the form with those fields is:

    print textfield({-name=>'start_date', -value=>$start_date});
    print textfield({-name=>'end_date', -value=>$end_date});

Then it goes to the database query.

Is there a simple, Perl-ish way to validate those dates? Not only as having the right number of characters, as this is simple enough via a regexp, but I'd like to report some error if the user enters 29.02.1999 or so.

A: 

FormFu seems to be the popular library for handling forms in Perl these days. I believe it replaces the CGI HTML generation code, but it is quite powerful.

It includes a bunch of code for validating common data types, including dates.

David Dorward
A: 

You can calculate dates in Perl with Time::Local, which can be set to accept invalid times and still calculate the correct date (e.g. the 32th day of a month) or the check the dates and reject invalid dates.

Alex Lehmann
+1  A: 

I'll just go ahead and own up to being crazy, but what I like to do is use Time::Local, and flip the time back to epoch time, and then, when it's a nice clean integer, you can impose whatever sort of sanity check you like on it.

Satanicpuppy
+1  A: 

For general form validation you should use a nice framework like Data::FormValidator which has a Data::FormValidator::Constraints::DateTime module for date validation

Disclosure: I'm the author of Data::FormValidator::Constraints::DateTime

mpeters
A: 

I nearly always opt to convert something like this into DateTime object. And I use something like DateTimeX::Easy to help ease the process:

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 bit hefty on memory which is something you may want to keep an eye on when using it in CGI.

/I3az/

draegtun