slok has asked for the wisdom of the Perl Monks concerning the following question:

I am using the CGI module. In my perl script, I take in a "year" field from the form. 1. How can I check that this is a valid year? ie not greater than current year?

2006-03-21 Retitled by planetscape, as per Monastery guidelines
Original title: 'date question'

Replies are listed 'Best First'.
Re: How to validate the year of a date?
by gmax (Abbot) on May 09, 2002 at 06:46 UTC
    You can get the current year using localtime, and then compare it to the form field.
    Before comparing, though, you should check that the year field is numeric.
    my $yearfield = get_it_from_somewhere(); my $current_year = (localtime)[5] + 1900; die "invalid number\n" unless $yearfield =~ /^\d+$/; die "invalid year\n" if $yearfield > $current_year;
    See the localtime page for more details.

    HTH
     _  _ _  _  
    (_|| | |(_|><
     _|   
    
      The "invalid number" test should probably be a little more picky:
      ... unless $yearfield =~ /^\d{4}$/;
      or maybe the user should be indulged when entering strings like "02", "99", etc, which entails something messier, like:
      ... unless $yearfield =~ /^(\d{2}){1,2}$/; if (length($yearfield) == 2) { $millen = ( $yearfield =~ /^0/ ) ? "20" : "19"; $yearfield = $millen . $yearfield; } ...
      (In this case, naturally, one shouldn't expect this script to still be in use after 2009, nor should users ever want to refer to years in the 19th century -- I have no problem with that.)