footpad has asked for the wisdom of the Perl Monks concerning the following question:
The apprentice, after again struggling for quite some time, caves...
Consider, if you will:
#! /usr/bin/perl -wT use strict; use CGI qw( :standard ); my $testvalue = ''; printForm(); if ( param() ) { br(); $testvalue = param( 'TestValue' ); my $errors = ""; $errors .= paramCheck( "Test Value", $testvalue, 1, 30, '/\W/', "letters and numbers" ); if ( $errors ) { print p( "Failed" ), "<UL>$errors</UL>" } else { print p( "Passed...wow, what a surprise." ); } } exit 1; sub paramCheck # Returns "" if no error or description of problem(s). { my $lbl = shift; # Field name for error messages my $val = shift; # Value received from the CGI query my $min = shift; # Minimun length; Use >0 for required fields my $max = shift; # Maximum allowed length my $pat = shift; # Regex to validate the data against. my $msg = shift; # Explanation added to error if Regex fails. my $err = ""; # Holds error message my $len = length( $val ); if ( $min ) # <> 0 { if ( $len < $min ) { $err .= wes( "$lbl cannot be blank." ); } } elsif ( $len > $max ) { my $s = $len == 1 ? "" : "s"; $err .= wes( "$lbl is currently $len character$s; " . "; it can only be $max character$s long." ); } else { unless ( $val =~ $pat ) { $err .= wes( "$lbl contains invalid characters; " . "it can only hold $msg." ); } } return $err; } sub printForm { print header(), start_html( -title => 'Test' ); print start_form( "post", "/cgi-bin/valtest.cgi", "application/x-www-form-urlencoded" ); print p( 'Enter a value:' ), textfield( 'TestValue', $testvalue, '40', '30' ); print br(), submit( "Try it" ), ' ', reset( "Reset" ); print end_form(); print end_html(); } sub wes # Wrap an Error String with desired tags. { my $input = shift; return "<LI>" . $input . "</LI>"; }
The idea, of course, is to devise a routine that handles the bulk of my CGI parameter validation. Unfortunately, I'm not seeing the results I expect with the regular expression in this example. Specifically, it always claims to match, even though I submit values such as "~", "/", "\", and so on (characters I'm specifically trying not to accept--hence the \W.)
My petitions are:
--f
P.S. Possibly relevant details: Perl v5.005_03, CGI v2.753, BSD 4.2.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Dynamic Regex?
by Kanji (Parson) on May 20, 2001 at 08:04 UTC | |
|
Re: Dynamic Regex?
by Albannach (Monsignor) on May 20, 2001 at 08:07 UTC | |
|
Re: Dynamic Regex?
by tachyon (Chancellor) on May 20, 2001 at 10:42 UTC | |
by chipmunk (Parson) on May 20, 2001 at 20:03 UTC | |
by tachyon (Chancellor) on May 21, 2001 at 05:06 UTC | |
|
Validating/cleaning input with tr
by Anonymous Monk on May 21, 2001 at 13:06 UTC |