Learning Perl the right way, part IX:
Task: untaint and validate user input using subroutines in a separate module.
Note: Because I eventually want to render the form with HTML::Template, listing the errors, I'm keeping track of the error messages for a
<tmpl var> in my
form.tmpl template file. So, after I get the data, I pass it, a literal for the error listing, and an array element for the actual message.
Monasterical questions: basically, is this code representative of "good practices" or efficient coding? Specifically, is my scoping, use of variables, passing of data, logic, and structure okay? Other comments?
use strict;
require "Validate.pm";
use CGI qw(:standard);
new CGI;
my ($name, $phone, $email, $date, @errmsg, $errmsgs);
$name = param('name');
&val_alpha($name, "Last Name", $errmsg[0]);
$phone = param('phone');
&val_phone($phone, "Phone Number", $errmsg[1]);
$email = param('email');
&val_email($email, "E-mail Address", $errmsg[2]);
$date = param('date');
&val_date($date, "Birth Date", $errmsg[3]);
&error_page(@errmsg);
print "Errors:\n$errmsgs\n";
#handle errors
sub error_page {
for (@_) {
if ($_) { $errmsgs .= "$_\n" }
}
}
$template = HTML::Template->new(filename => "form.tmpl");
$template->param(errors => $errmsgs);
#eventually process and write to the database
__END__
And for the module:
#Validate.pm
sub val_alpha {
if ($_[0] =~ /^([A-Za-z -]*)$/) {
$_[0] = $1;
} else {
$_[2] = "Invalid character(s) in $_[1]";
}
}
sub val_phone {
if ($_[0] =~ /^[\(]?(\d{3})[\)\.\-]?(\d{3})[\)\.\-]?(\d{4})$/) {
$_[0] = "$1-$2-$3";
} else {
$_[2] = "Invalid $_[1]";
}
}
sub val_date {
if ($_[0] =~ /^(\d{2})-(\d{2})-(\d{4})$/) {
$_[0] = "$1-$2-$3";
} else {
$_[2] = "Invalid $_[1]";
}
}
sub val_email {
if ($_[0] =~ /^([\w\.\-]{3,})@([\w\.\-]{3,})\.([A-Z]{2,3})$/i) {
$_[0] = "$1\@$2\.$3";
} else {
$_[2] = "Invalid $_[1]";
}
}
1;
Thanks all in advance.
—Brad
"A little yeast leavens the whole dough."
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.