Hi Monks,

I've re-implemented the check user input sub Check input sub - comments please... to make it more flexible. Instead of passing the sanitize sub a list of scalars, I'm now passing it a hash to improve readability and to allow for some flexibility.

$username = sanitize( data => param('username'), # call from CGI form field => 'Username', # field name obligatory => 1, # field is obligatory min => 8, max => 8, regex => '%;&()#\w ', # customised regex ); sub sanitize { # date, field, obligatory, min, max, numeric, regex my %checks = @_; $checks{'data'} =~ s/\s+/ /g; # remove leading and trailing blanks $checks{'data'} =~ s/^\s+//; $checks{'data'} =~ s/\s+$//; # Default regex my $default = '-\@\w. '; $checks{'regex'} = $checks{'regex'} ? $checks{'regex'} : $default; # This part changed by graff my $length = length($checks{'data'}); if (!$length) { # empty string if ($checks{'obligatory'}) { bail_out("$checks{'field'} is obligatory"); } else { return; } } if ($checks{'data'} =~ /([^$checks{'regex'}])/) { bail_out("Bad input."); } if ($checks{'numeric'} and $checks{'data'} =~ /[^\d]/) { bail_out("Non-numeric character(s) in numeric field"); } if ($checks{'min'} and $length < $checks{'min'}) { bail_out("Too long."); } if ($checks{'max'} and $length > $checks{'max'}) { bail_out("Too short"); } return $checks{'data'}; }

All comments are welcomed :)

ps: I know great modules exist to do that sort of stuff. I just want to try and create something simple for my own use. I see it as part of my perl learning journey.

update 16 Dec 2003

Many thanks to all, especially to William G. Davis. My little user input checking code is now in a much better shape.


In reply to Check user input - reimplementation by kiat

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.