tomred has asked for the wisdom of the Perl Monks concerning the following question:
I have been wresting with a problem. I often need to parse and validate (string) data before inserting it into a DB. I've come to rely on Type::Tiny for this kind of validation.
In this case the data cannot be longer than x varchar(x). I often find the data is a empty etring, e.g. ''. If the data is an empty string, I would to rather return undef (null) than ''. In terms of terminology, I am not sure if this is a coercion or not. HTML::FormHandler has the notion of Transform(ations) but I haven't seen a means of appying transformations in the Moo world.
I have become stuck trying to finding a way to allow for a stirng to be either undefined, or if defined less than x or if an emtpy string, undefined.
It could be written a like (untested) this: $data = $_ eq '' ? undef : $_ < $x ? $_ : undef But I'd like to stick to the Types eco system albeit my grasp of it is somethimes failing. Here is my latest effort. The test warning because $_ is not numeric is tricky to side-step.use v5.22; use warnings; use Test::More; use Test::Deep; use Test::Warnings; use lib qw(lib t); use Type::Tiny; use Types::Standard qw( Maybe Str ); use Types::Common::String qw( NonEmptyStr ); use Type::Params qw( compile_named ); =head2 The goal is to allow a "caption", if defined, should be less than $cap +size. If caption == '', I'd like to return the value as undef. =cut my $capsize = 2781; # This will warn when $_ in not numeric my $LongCaption = Type::Tiny->new( name => 'Caption', constraint => sub { length($_) < $capsize }, message => sub { "Caption needs to be less than $capsize charac +ters" } ); my $EmptyStr = "Type::Tiny"->new( name => 'EmptyString', constraint => sub { $_ eq '' }, message => sub { "An empty string" } ); $LongCaption->plus_coercions( $EmptyStr => sub { warn "Coercing"; return undef; }, ); state $check = Type::Params::compile_named( caption => Maybe[$LongCaption], ); my $text = ''; my $val = $LongCaption->assert_return( $text ); note $val; is($val, undef, 'coerced into undef'); my $data = $check->( { caption => $text } ); cmp_deeply($data, { caption => undef }, 'coerced into undef'); done_testing;
Thanks in advance. I do hope I have not made a silly error.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Coerce or transform with Types::Param
by 1nickt (Canon) on Mar 19, 2021 at 21:03 UTC | |
by tomred (Acolyte) on Mar 20, 2021 at 13:04 UTC | |
by 1nickt (Canon) on Mar 20, 2021 at 14:34 UTC | |
|
Re: Coerce or transform with Types::Param
by tobyink (Canon) on Mar 21, 2021 at 11:00 UTC | |
by 1nickt (Canon) on Mar 21, 2021 at 12:41 UTC | |
by tomred (Acolyte) on Mar 21, 2021 at 15:23 UTC | |
by tomred (Acolyte) on Mar 21, 2021 at 15:25 UTC | |
by tobyink (Canon) on Mar 21, 2021 at 20:33 UTC |