Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Code Cleanup challenge!
by dws (Chancellor) on Aug 10, 2003 at 20:08 UTC | |
|
Re: Code Cleanup challenge!
by Zaxo (Archbishop) on Aug 10, 2003 at 17:17 UTC | |
by sauoq (Abbot) on Aug 10, 2003 at 21:44 UTC | |
by Aristotle (Chancellor) on Aug 11, 2003 at 21:32 UTC | |
by sauoq (Abbot) on Aug 11, 2003 at 21:38 UTC | |
|
Re: Code Cleanup challenge!
by monktim (Friar) on Aug 11, 2003 at 13:49 UTC | |
by kesterkester (Hermit) on Aug 12, 2003 at 17:33 UTC | |
|
Re: Code Cleanup challenge!
by Anonymous Monk on Aug 10, 2003 at 19:30 UTC | |
|
Re: Code Cleanup challenge!
by Willard B. Trophy (Hermit) on Aug 11, 2003 at 18:33 UTC |