kiat has asked for the wisdom of the Perl Monks concerning the following question:
I wrote the sub below to check for user input. It's a rather restrictive check as only alphanumeric characters and a small set of non-word characters are allowed. It also checks for obligatory fields, minimum and maximum characters permitted and whether an input should be numeric.
I'm seeking your opinion on whether the coding practice I adopt is a sound one and if not, how should I change it. It works with limited testing. Please feel free to comment on my code.
# The meaning of each argument # ($data, $field, $obligatory, $min, $max, $numeric) # Username is obligatory, must be at least 2 character long # and must not be more than 30 characters (note that the # numeric is undef so a username can be numbers. my $username = sanitize(param('username'), 'Username', 1, 2, 30); # Level must be a single character and must be numeric my $level = sanitize(param('level'), 'Level', 1, 1, 1, 1); sub sanitize { # $data may contain evil characters my ($data, $field, $obligatory, $min, $max, $numeric) = @_; $data =~ s/\s+/ /g; # Remove extra spaces to nothing $data =~ s/ +//g; # remove leading and trailing blanks $data =~ s/^\s+//; $data =~ s/\s+$//; # If data contains something if ($data) { if ($data =~ /^([-\@\w. ]+)$/) { # Check length my $length = length($data); if ($min || $max) { if ($min == $max) { bail_out("Data does not meet the required length.") if ($len +gth != $min); } if ($min && $length < $min) { bail_out("Too short.") } if ($max && $length > $max) { bail_out("Too long.") } } if ($numeric) { bail_out("Data must be numeric.") if ($data !~ /^\d*$/); } return $data; } else { bail_out("Bad data."); } } # If data is an empty string else { if ($obligatory) { bail_out("Data at $field is empty."); } else { return undef; } } }
|
|---|