I'm validating user input through forms via CGI using the following script I wrote:
#!/usr/bin/perl -wT use strict; use CGI; my $q = new CGI; # keys are param names # values are regexes matching allowed content and max allowed length my %required_params = ( 'name' => ['(\w+)', '255'] ); my %optional_params = (); my %validated_params = (); # ensure all required params have been received, validate them for my $param (keys %required_params) { unless ($q->param($param)) { error("Missing parameter $param\n"); } my $regex = $required_params{$param}; if ($q->param($param) =~ /$regex/) { $validated_params{$param}[0] = $q->param($param); } else { error("Invalid structure for parameter: $param"); } unless (length($q->param($param)) <= $required_params{$param}[1]) +{ error("Parameter: $param is too long\n"); } } # validate all optional params for my $optional_param (keys %optional_params) { my $regex = $optional_params{$optional_param}[0]; if ($q->param($optional_param) =~ /$regex/) { $validated_params{$optional_param} = $q->param($optional_param +); } else { error("Invalid structure for parameter: $optional_param"); } unless (length($q->param($optional_param)) <= $optional_params{$op +tional_param}[1]) { error("Parameter: $optional_param is too long\n"); } } output_page(); sub error { # overkill, but allows flexibility in the future my $error = shift; print "Error: $error"; exit(); } sub output_page { # change to templating system for anything more than a few lines print <<EOF; <html> <head> <title>Thanks!</title> </head> <body> <p>Thank you for your input.</p> <p><a href="index.html">Return home</a></p> </body> </html> EOF exit(); }
I'd really like to clean this code up but I'm not quite sure how. The one thing that comes to mind is to split each validation step up into subs. So I'd have a validate_length, validate_content, and exists sub of some kind. I'm not sure that would solve the problem though. I also don't know how I'd go about validating the optional and required parameters in the same loop.
I'd appreciate any suggestions you have :)
Edit by tye, added READMORE, moved from Meditations
In reply to Code Cleanup challenge! by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |