#! /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" ), "" } 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 "
  • " . $input . "
  • "; }