In this fifteenth slide, we introduce a form validator which either displays
the form validator or execute the CGI program processing it, based on a simple
test:
if (%qx) { process the form } else { display the form }
1. THE FORM VALIDATOR:
The program consists of three parts:
In Part I, we use the CGI library to evaluate the variable pairs and check
if the form was submitted:
#!/usr/local/bin/perl
use CGI qw(:standard);
$query=new CGI;
print $query->header;
print "<html><head><title>Form Validator</title></head>\n";
print "<body>";
print "<h1>Form Validator<h1>\n";
foreach $ii (sort $query->param())
{
$jj=$query->param($ii);
$qx{$ii}=$jj;
#print "${ii}: ${jj}<br>";
}
In Part II, we assume that the form was submitted:
if (%qx)
{
$ssn=$qx{'ssn'};
print "You entered SSN#: $ssn<br>";
if ((length($ssn) == 9) && ($ssn =~ /^[0-9]+$/))
{
print "Valid Social Security Number.\n";
}
else
{
print "Invalid Social Security Number.\n";
}
}
and in Part III, we assume that the form is displayed for the first time:
else
{
print "<form>\n";
print "Social Security Number:\n";
print "<input type=\"text\" name=\"ssn\">\n";
print "<input type=\"submit\">\n";
print "</form>\n";
}
print "</body></html>";
2. FORM DESCRIPTION:
In Part I, the most important section is a foreach statement where the
variable pairs are read into an associative array: %qx:
foreach $ii (sort $query->param())
{
$jj=$query->param($ii);
$qx{$ii}=$jj;
#print "${ii}: ${jj}<br>";
}
If the form was submitted, the associative array is not empty, we go to
part II, we validate the form and display a validation message:
if ((length($ssn) == 9) && ($ssn =~ /^[0-9]+$/))
{
print "Valid Social Security Number.\n";
}
else
{
print "Invalid Social Security Number.\n";
}
If not, we go to part III, and display the form:
print "<form>\n";
print "Social Security Number:\n";
print "<input type=\"text\" name=\"ssn\">\n";
print "<input type=\"submit\">\n";
print "</form>\n";
3. PROGRAM EXECUTION:
Access the program by clicking on the following link:
Form Validator
or, using your browser, type the following URL:
http://www.claywall.com/cgi-bin/CGI/validate.cgi
|