http://www.perlmonks.org?node_id=954264


in reply to Script to validate date fails

$date =~ /[1-31]-[1-12]-[1-99]/; doesn't do what you want.

[...] is used for class of characters : you must list characters one-by-one "abcd" or a range like "a-k" or "0-6" (see http://perldoc.perl.org/perlrecharclass.html => 1) Bracketed Character Classes -- 2) Character Ranges )

Here is a "DIY" validation :

$date =~ /(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-(\d?\d)$/

(0?[1-9]|[12][0-9]|3[01]) means...

accepts :
1 to 9 with an optional 0 prefix => 01,02,03...09 and 1,2,3...9
*OR*
(1 or 2) before (0 to 9) => 10,11,...,29
*OR*
30 or 31

...but it's not the good way to do it (what about 29-02-01 for example?) It's better to use a module which knows the calendar.

Last thing : year with 2 digits ? not good ! :)

My first try :

#!/usr/bin/perl use DateTime; print ("Enter the date in dd-mm-yyyy format : ") ; $date = <STDIN> ; chomp ($date) ; while ($date ne "") { my ($d,$m,$y) = split '-',$date; warn "/!\\ wrong year format? $y\n" if $y!~/^\d{4}$/ ; if ( eval {DateTime->new(year=> $y,month=> $m, day=> $d)} +) { print("You have entered valid data \n") ; } else { print ("You have entered invalid data \n") ; } $date = <STDIN> ; chomp($date) ; }