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");

In reply to Re: date validation module by ikegami
in thread date validation module by arcnon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.