$username = sanitize( data => param('username'), # call from CGI form field => 'Username', # field name obligatory => 1, # field is obligatory min => 8, max => 8, regex => '%;&()#\w ', # customised regex ); sub sanitize { # date, field, obligatory, min, max, numeric, regex my %checks = @_; $checks{'data'} =~ s/\s+/ /g; # remove leading and trailing blanks $checks{'data'} =~ s/^\s+//; $checks{'data'} =~ s/\s+$//; # Default regex my $default = '-\@\w. '; $checks{'regex'} = $checks{'regex'} ? $checks{'regex'} : $default; # This part changed by graff my $length = length($checks{'data'}); if (!$length) { # empty string if ($checks{'obligatory'}) { bail_out("$checks{'field'} is obligatory"); } else { return; } } if ($checks{'data'} =~ /([^$checks{'regex'}])/) { bail_out("Bad input."); } if ($checks{'numeric'} and $checks{'data'} =~ /[^\d]/) { bail_out("Non-numeric character(s) in numeric field"); } if ($checks{'min'} and $length < $checks{'min'}) { bail_out("Too long."); } if ($checks{'max'} and $length > $checks{'max'}) { bail_out("Too short"); } return $checks{'data'}; }