kiat has asked for the wisdom of the Perl Monks concerning the following question:
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.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Check user input - reimplementation
by hanenkamp (Pilgrim) on Dec 15, 2003 at 13:39 UTC | |
|
Re: Check user input - reimplementation
by Roy Johnson (Monsignor) on Dec 15, 2003 at 18:08 UTC | |
by kiat (Vicar) on Dec 15, 2003 at 23:25 UTC | |
by Roy Johnson (Monsignor) on Dec 16, 2003 at 21:26 UTC | |
|
Re: Check user input - reimplementation
by ysth (Canon) on Dec 15, 2003 at 18:08 UTC | |
|
Re: Check user input - reimplementation
by YuckFoo (Abbot) on Dec 15, 2003 at 18:48 UTC | |
by kiat (Vicar) on Dec 15, 2003 at 23:28 UTC | |
|
Re: Check user input - reimplementation
by William G. Davis (Friar) on Dec 15, 2003 at 19:03 UTC | |
by kiat (Vicar) on Dec 15, 2003 at 23:18 UTC | |
by William G. Davis (Friar) on Dec 16, 2003 at 13:03 UTC |