I've re-implemented the check user input sub Check input sub - comments please... to make it more flexible. Instead of passing the sanitize sub a list of scalars, I'm now passing it a hash to improve readability and to allow for some flexibility.
$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'}; }
All comments are welcomed :)
ps: I know great modules exist to do that sort of stuff. I just want to try and create something simple for my own use. I see it as part of my perl learning journey.
update 16 Dec 2003
Many thanks to all, especially to William G. Davis. My little user input checking code is now in a much better shape.
In reply to Check user input - reimplementation by kiat
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |