in reply to Re^3: Brannigan: hash validation
in thread Brannigan: hash validation
Hi again,
First, be sure to check Type::Params for a more user-friendly way to use the types and type libraries you create (and the standard ones) in validating parameters to a function. Second, be sure to review all the docs, including the cookbooks. There's actually quite a lot, just not well collated centrally. You'll also find good examples in the archives of the Perl Advent Calendar.
Type RegexpRef tests only whether it is passed a compiled regexp, i.e. with qr//, not the content of the regexp. Use StrMatch for that.
You can always declare your own types, as well as your own type library. Here I declare a type that requires an array ref, and that it be of a certain length.
Output:# ~/monks/1209129.t package MyTypes { use parent 'Type::Library'; use Type::Utils; use Types::Standard qw/ ArrayRef Dict Enum Str StrMatch /; my $MyArray = Type::Tiny->new( as => 'ArrayRef', name => 'ClientArray', constraint => sub { scalar @{ $_ } == 2 }, ); declare MyType => as Dict[ method => Enum['xxx'], backend => Dict[ client => StrMatch[qr/\d{3}/], pw => Str, ], clientArr => $MyArray, ]; # If you want to be able to use the new type independently by name +: __PACKAGE__->meta->add_type($MyArray); __PACKAGE__->meta->make_immutable; }; package main { use Test::Most; use JSON; # normally, load as normal with `use MyTypes '+MyType'` MyTypes->import(qw/ +MyType /); while ( <DATA> ) { my ( $label, $json ) = split / => /; chomp $json; my $data = from_json $json; if ( $. == 1 ) { ok eval { assert_MyType( $data ); 1 }, $label; } else { ok ! eval { assert_MyType( $data ); 1 }, $label; } } done_testing; }; __END__ Valid data => {"method":"xxx","backend":{"client":"mytest009","pw":"sd +kjfhsfjhKJH87"},"clientArr":[{"num":"1"},{"num":"2"}]} Unknown key => {"method":"xxx","backend":{"client":"mytest009","pw":"s +dkjfhsfjhKJH87"},"clientArr":[{"num":"1"},{"num":"2"}],"blah":"123"} Failed regexp => {"method":"xxx","backend":{"client":"mytest09","pw":" +sdkjfhsfjhKJH87"},"clientArr":[{"num":"1"},{"num":"2"}]} Not an array => {"method":"xxx","backend":{"client":"mytest009","pw":" +sdkjfhsfjhKJH87"},"clientArr":{"foo":{"num":"1"},"bar":{"num":"2"}}} Array too long => {"method":"xxx","backend":{"client":"mytest009","pw" +:"sdkjfhsfjhKJH87"},"clientArr":[{"num":"1"},{"num":"2"},{"num":"3"}] +}
$ prove -v ~/monks/1209129.t ok 1 - Valid data ok 2 - Unknown key ok 3 - Failed regexp ok 4 - Not an array ok 5 - Array too long 1..5 ok All tests successful. Files=1, Tests=5, 1 wallclock secs ( 0.03 usr 0.00 sys + 0.13 cusr + 0.02 csys = 0.18 CPU) Result: PASS
Hope this helps!
|
|---|