Mike Gossland's Perl Tutorial Course for Windows


Intro to GET | CGI Module | Handling Forms | Form Errors | Fatal Errors


Chapter 6. The CGI Module

Handling Form Errors

Sometimes when a user is filling in a form, he or she will leave out a crucial field or provide erroneous information. It's a fact of life that it's up to you to deal with it.

The best first line of defense against blank inputs is Javascript because the server doesn't even have to get involved in the correction. But sometimes, like when a user selects a username that's already taken, the only way to know there's an error is to check the data on the server.

Once you find an error, you have to prompt the user to enter the data again. You could just put up the original form and ask them to fill in the whole thing, but you'd be very unpopular with that approach. It's much better to fill in the form with the information they already provided, and just prompt them to correct the parts that are wrong.

Substitution of provided form fields is all that's needed for this. Let's say you put up a the same form as we've seen before, but with a twist: you'll be expected to fill in your name if you didn't provide it.


#!/usr/bin/perl
use CGI;
use CGI::Carp qw(fatalsToBrowser);

$cgi = new CGI;

for $key ( $cgi->param() ) {
	$input{$key} = $cgi->param($key);
}

print qq(Content-type: text/html\n\n);

if ( $input{name} ) {

	$new_html  = qq(<p><blockquote><font color="red">);
	$new_html .= qq(You are $input{name}\n);
	$new_html .= qq(<p>You wish to be a $input{animal}\n);
	$new_html .= qq(<p>You pushed the $input{request} button);
	$new_html .= qq(</font></blockquote>\n<p>);

	open HTML, "../course/cgi_module/form_errors.html";

	while ( <HTML> ) {

		s/<!-- example3substitution -->/$new_html/;
		
		print;

	}

	close HTML;

} else {

	open HTML, "../course/cgi_module/example3.html";

	while ( <HTML> ) {

		# add an explanation
		s{<body>}{<body><p><font color="red">
		          Put in your name or be a ding-bat</font><p>};

		#restore the selected option
		s{<option value="$input{animal}"}
		 {<option value="$input{animal}" selected};
		
		print;

	}

	close HTML;
}


Now that you've seen how to handle the users errors, you can take what you have learned to handle your own.