Database Reference
In-Depth Information
Server-Side Versus Client-Side Validation
As described in Recipe 12.1 , you can cause data validation to be done on the server side
by setting the SQL mode to be restrictive about accepting bad input data. In this case,
the MySQL server raises an error for values that are invalid for the data types of the
columns into which you insert them.
In the next few sections, the focus is validation on the client side rather than on the
server side. Client-side validation can be useful when you require more control over
validation than simply receiving an error from the server. (For example, if you test values
yourself, it's often easier to provide more informative messages to users about the exact
nature of problems with the values.) Also, it might be necessary to couple validation
with reformatting to transform complex values so that they are compatible with MySQL
data types. You have more flexibility to do this on the client side.
Writing an input-processing loop
Many of the validation recipes shown in the new few sections are typical of those that
you perform within the context of a program that reads a file and checks individual
column values. The general framework for such a file-processing utility looks like this:
#!/usr/bin/perl
# loop.pl: Typical input-processing loop.
# Assumes tab-delimited, linefeed-terminated input lines.
use strict ;
use warnings ;
while ( <> ) # read each line
{
chomp ;
# split line at tabs, preserving all fields
my @val = split ( /\t/ , $_ , 10000 );
for my $i ( 0 .. @val - 1 ) # iterate through fields in line
{
# ... test $val[$i] here ...
}
}
The while() loop reads each input line. Within the loop, each line is broken into fields.
( Recipe 11.7 discusses why split() is written as it is.) The inner for() loop iterates
through the fields, enabling each to be processed in sequence. If you don't apply a given
test uniformly to all the fields, replace the for() loop with separate column-specific
tests.
 
Search WWH ::




Custom Search