Assuming the text box is named "bob", you could use something like the following (untested):
#!/usr/bin/perl -wT
use strict;
use CGI;
use HTML::Entities;
my $query = CGI->new;
my $tainted_number = $query->param( "bob" );
my ( $clean_number ) = ( $tainted_number =~ /^\s*(\d+)\s*$/ );
print $query->header,
$query->start_html( -title => "Input test" );
if ( defined $clean_number ) {
print $query->p( "You entered '$clean_number'." );
} else {
print $query->p( "You're only supposed to enter numbers, dummy." )
+,
$query->p( "You entered '" . encode_entities( $tainted_numbe
+r ) . "'" );
}
print $query->end_html;
At this point, $clean_number will either contain a string composed only of digits, or will be undef if the data entered in "bob" does not pass validation.
HTML::Entities is used to ensure that the user-supplied data does not interpret as HTML (for example, it converts <> to <>).
See perlsec if you're unsure about why I used the -T switch.
Cheers,
Ovid
Join the Perlmonks Setiathome Group or just click on the the link and check out our stats. |