Data Validation

Dave Doyle
dave.s.doyle@gmail.com

OANDA Corp.

Data Validation

Params::Validate

Params::Validate - Positional

use Params::Validate qw(:all);

sub foo {
    #my $self = shift; # shift $self off first if OO
    my ($name, $age ) = validate_pos(@_,
        {
            type      => SCALAR,
            callbacks => {
                'min_length' => sub { return length($_[0]) >= 6;  },
                'max_length' => sub { return length($_[0]) <= 12; },
            },

        },
        { type => SCALAR, regex => qr/^\d+$/, optional => 1 },
    );
    print $name, '; $age ', (defined $age ? '' : 'not ' ), "defined.\n";
}

foo('yeehaw' );        #> yeehaw; age not defined
foo('yeehaw', 1);      #> yeehaw; age defined
foo("yaaaaay", 'i');   # fails regex check
foo("short" );         # fails min_length check
foo("looooooooooong"); # fails max_length check
foo([]);               # fails type check
foo(undef);            # fails type check
    

Params::Validate - Named

use Params::Validate qw(:all);

sub foo {
    #my $self = shift; # shift $self off first if OO
    my %args = validate(@_, {

        name => { type => SCALAR, regex => qr/^.{6,12}$/s },
        age  => { type => SCALAR, regex => qr/^\d+$/, optional => 1 },
    });
    print $args{name},
        '; age ',
        (defined $args{age} ? '' : 'not ' ),
        "defined.\n";
}

foo( name => 'yeehaw' );               #> yeehaw; age not defined
foo( name => 'yeehaw' );               #> yeehaw; age not defined
# unrolls if passed a hashref
foo( { name => 'yeehaw', age => 1 } ); #> yeehaw; age defined
    

Params::Validate - basic checks

Params::Validate - types of checks

Params::Validate - types of checks

Params::Validate - types of checks

Params::Validate - types of checks

Params::Validate - validate_with

  my %p =
      validate_with
          ( params => \@_,
            spec   => { foo => { type => SCALAR },
                        bar => { default => 10 } },
            allow_extra => 1,
            called => 'The Quux::Baz class constructor',
          );

  my @p =
      validate_with
          ( params => \@_,
            spec   => [ { type => SCALAR },
                        { default => 10 } ],
            allow_extra => 1,
            called => 'The Quux::Baz class constructor',
          );
    

Thank you.