I wrote this simple lil' diddy as a reusable module to check required fields and 
wanted to share it.  You can put this in a central .pl file to be required by any CGI 
script that needs to verify that certain fields have been filled out.  Probably makes 
more sense to do this type of verification through JavaScript on the client-side, but 
I'm not as familiar with that.

You just need to create a hash with left-values of the INPUT name from the form and 
right-values of a long-form/presentable form of the field.  Then you can call this 
routine with 2 parameters - the CGI object [requires CGI] and the hash of your 
required fields.

I also added support for a left value with ||'s - meaning if you have a situation (as 
I did) where one of two fields has to be required, but not both.

You may also want to modify the code to format the output/behavior of the clause of 
when a form is incomplete.

I am a sorta-newbie (experienced, but rusty), so I'm sure there are better ways to 
write the code or even if the code is written into some other module out there.

HTH,

Jason

------------------------------------
Example Hash:
%requiredFields = (
    'upload_file'                   => 'Document Source',
    'doc_url||docfile'            => 'Specify either Document URL or Document File',
    'capture_date'               => 'Capture Date' );

------------------------------------
Example Usage:
#!/usr/local/bin/perl

use CGI;
require 'rfields.pl';

$query = new CGI;

# let's start by checking the required fields
checkRequiredFields($query, %requiredFields);

...

------------------------------------
Code:
sub checkRequiredFields {
    my ($formHandle, %reqdFields) = @_;
    my ($incomplete) = 0;
    my (@incFields) = ();
    
    foreach $field (keys %reqdFields) {
        if ($field =~ /(.*)\|\|(.*)/) {
            $incomplete = 1 && push (@incFields, $reqdFields{$field})
                if ( (!$formHandle->param($1) || $formHandle->param($1) eq '') &&
                     (!$formHandle->param($2) || $formHandle->param($2) eq '') );
        } else {
            $incomplete = 1 && push (@incFields, $reqdFields{$field})
                if !$formHandle->param($field) || $formHandle->param($field) eq '';
        }
    }

    if ($incomplete) {
        print "<H2>Incomplete Form</H2>\n";
        print "You missed the required fields:<BR>\n<UL>\n";
        foreach $incField (@incFields) { print "<LI>$incField\n"; }
        print "</UL>\n";
        print "<CENTER><I>Use your browser's back button & try again</I></CENTER>\n";
        exit;   # I couldn't just use the die, b/c it wouldn't format the $msg like I 
wanted
    }
}

Reply via email to