Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: Script to validate date fails

by brx (Pilgrim)
on Feb 16, 2012 at 15:49 UTC ( #954264=note: print w/ replies, xml ) Need Help??


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


Comment on Re: Script to validate date fails
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://954264]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2014-10-01 22:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    What is your favourite meta-syntactic variable name?














    Results (40 votes), past polls