Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

In MySQL, which does not support any kind of data integrity constraints, you have to ensure that all the data sent to the DB is validated by the scripts (required fields not empty, invalid characters, etc).

In particular, I am interested in knowing the best/common way of making sure that all the fields that are sent to the DB have data on it. If not, then the update/insert should not occur.

Thanks in advance.

  • Comment on What is the best way to validate data ?

Replies are listed 'Best First'.
Re: What is the best way to validate data ?
by Russ (Deacon) on Aug 06, 2000 at 23:26 UTC
    How do I detect and handle empty form fields? asks a similar question. It is more specifically CGI-related, but...

    my @InvalidFields = grep {not defined CGI::param($_) or CGI::param($_) eq ''} CGI::param +();

    @InvalidFields will now contain the names of any empty fields.

    If you are not working with CGI, just replace the param calls with appropriate data structures.

    my @InvalidFields = grep {not defined $Hash($_) or $Hash($_) eq ''} keys %Hash;
    Russ
Re: What is the best way to validate data ?
by juahonen (Novice) on Aug 09, 2000 at 11:45 UTC
    Handling NULL fields is an issue with any database. Since an undef produces zero-length output, it cannot be sent to the database (the SQL statement would look like 'COLUMN=,OTHER=' which is not what the DB wants).
    Null fields can be handled in a simple statement: $nullable = 'NULL' unless $nullable;
    This will eliminate the nasty error when you're setting DB columns to undefs...
    You could also use "COLUMN='$nullable'" for strings, but that would store zero length string in the database instead of NULL making queries much more comples (you'll need to check agains both empty strings and NULLs for unset values).

    Strings can be handled the same way by adding the quotion marks to the string variable intead of the SQL insert (enabling NULL fields to be inserted):
    $string_var = "'$string_var'" if $string_var;

    Of course, if the string can be null, the quotation marks need to be added before the string is verified against undef or you'll have columns with 'NULL' values instead of NULL.

    To make things simple, create a function which does validation. If you need to stop on missing fields, use the code suggested by Russ.