You can never trust any data that comes from outside of your program. That especially goes for HTML forms. Your program needs to know what parameters are expected in the script, and it needs to check the values to make sure they are valid.

This is actually easier to do than it seems with a module like Data::FormValidator. Here is a quick example, but have a read of the documentation for more details.

my $profile = { required => [qw( cc_type cc_name cc_number cc_expiry cc_3digit_code )], constraints => { # field must match one of visa amex or mc cc_type => qr/^(visa|amex|mc)$/, # match to a name cc_name => qr/^([\w ]+)$/, # use built in cc_number function to validate # credit card numbers. the validation # routine needs both the cc_number and the # cc_type to do the validation cc_number => { constraint => 'cc_number', params => [qw(cc_number cc_type)] }, # use the builting cc_exp routine to validate # the expiry date cc_expiry => 'cc_exp', # field must be a 3 or 4 word or # digit characters cc_3digit_code => qr/^([\w\d]{3,4})$/, }, }; # Check the profile to make sure everything was filled in correctly my $query = CGI->new(); my $results = Data::FormValidator->check($query, $profile); if ($results->has_invalid or $results->has_missing) { # There were some problems with the form values # so redisplay the form ... } else { # The form was properly filled out my $valid = $results->valid(); # now $valid contains a hashref of all the validated data # so do something with the values ... }

The above is a simple example of how to validate credit card details.

- Cees


In reply to Re: CGI form data validation by cees
in thread CGI form data validation 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.