Wednesday, June 6, 2012

Using Data::Validate Modules to Validate Application Data

In an earlier approach I provided A Brief Introduction to Input Validation where the basic concepts of whitelisting and blacklisting were introduced to readers.  While every programmer should be familiar with the idea of writing input validation filters it can often be challenging to develop a filter that minimizes both the numbers of false positives as well as the number of false negatives, and thus it often pays to use well tested routines for input validation where feasible.   CPAN contains many such routines that can usually be located by searching CPAN for terms like Valid, Validate, Validator, and Validation.  One CPAN namespace in particular that has many useful routines is the Data::Validate namespace, which contains routines for validating numbers, IP addresses, email addresses, URLs and more.  In the code snippet below we will take a look at the Data::Validate::IP ( and the Data::Validate::Email ( Perl modules.  


use strict;
use warnings;

use Data::Validate::IP qw(is_ipv4);

my @IPs=('','','','abc.123.123.123');
foreach my $IP (@IPs){
        print "$IP is a valid ipv4 address\n";
        print "$IP is invalid\n";

use Data::Validate::Email qw(is_email);
my @Emails=('','someone&','someone@example.123','');
foreach my $Email (@Emails){
        print "$Email is a valid Email address\n";
        print "$Email is invalid\n";

Once you select a validation method for your application it is also imperative that you take the time to test your validation routine to make sure that valid inputs are properly passed on to the application and that any invalid inputs are flagged as such.  Such testing should involve both use cases as well as “abuse” cases designed to try to bypass the filter.  The need for testing is especially true if you decide to implement your own validation routine as it is not always easy to think off all the possible ways somewhat could attempt to format an input string.  Remember that input validation is typically an application’s front line defense in that it exists to minimize the risk of improper or malicious data from ever being processed by the application. 

1 comment:

Unknown said...

This example is easy for understanding