# 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 ($length != $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; } } }