I know there's already a CPAN module that does this, and I know there's plently of people out there who have reinvented this wheel many times, but while hacking a quick user registration thing for a site, I wrote this bit of code, I thought other might find it useful...
Takes two arguments, a ref to a CGI object (or anything that implements param with the same semantics as CGI) and a ref to a hash of (key, valitation) pairs.
sub validate_data($$) { my $q = shift; my $tmpl = shift; my %data = (); my %invalid = (); foreach my $key (keys %{$tmpl}) { my $value = $q->param($key); if (&{$tmpl->{$key}}($value)) { $data{$key} = $value if defined $value; } else { $invalid{$key} = 1; } } return (\%data, \%invalid); }
And the validation routines are:
sub is_string { return sub { return $_[0] ne ""; }; } sub is_number { return sub { return $_[0] =~ m{^\d+$}; }; } sub is_range($$) { (my $l, my $u) = @_; return sub { return $_[0] =~ m{^\d+$} && $_[0] >= $l && $_[0] <= $u; }; } sub is_in_list($) { my $l = shift; return sub { return (grep { $_[0] eq $_ } @{$l}) != 0; }; } sub is_email { return sub { return $_[0] =~ m{^[-.+a-z0-9]+\@[-.+a-z0-9]+$}i; }; } sub is_required { my $t = shift; return sub { defined $_[0] and &{$t}($_[0]); }; } sub is_optional { my $t = shift; return sub { return defined $_[0] ? &{$t}($_[0]) : 1; }; } sub is_equal { my $v = shift; return sub { $_[0] eq $v ? 1 : 0; } }
The "is_equal" routine probably needs to be generalized to be able to compare numbers and other things... You can use it like this:
my %fields = ( name => is_required(is_string()), email => is_required(is_email()), phone => is_optional(is_phone()), );

In reply to Validate CGI data by marcelo.magallon

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.