blib/lib/FormValidator/Tiny.pm

filter: Statementstmt 99.2% 379 / 383 (1 uncoverable) Branchbran 91.0% 182 / 200 Conditioncond 83.7% 67 / 80 MC/DCmcdc 70.2% 33 / 47 Subroutinesub 100% 85 / 85 Podpod 100% 9 / 9 totaltotal 94.0% 755 / 804 (1 uncoverable) CC 135 SCAR 23.9
CC
135
Cov
95%
validation_spec
36.0
validate_form
19.8
number_in_range
16.0
CRAP 10.9
↑ Summary
1 package FormValidator::Tiny;
2 23 $FormValidator::Tiny::VERSION = '0.004';
3 23 ▶use v5.18;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 23 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 23 ▶use List::Util qw( any pairs pairgrep pairmap );
Subroutine BEGIN: called CC=1 SCAR=0.0
7 23 ▶use Scalar::Util qw( blessed looks_like_number );
Subroutine BEGIN: called CC=1 SCAR=0.0
8 23 ▶use experimental qw( regex_sets );
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 23 ▶use Exporter;
Subroutine BEGIN: called CC=1 SCAR=0.0
11  
12 23 ▶BEGIN {
Subroutine BEGIN: called CC=1 SCAR=0.0
13 23 our @ISA = qw( Exporter );
14 23 our @EXPORT = qw( validation_spec validate_form );
15 23 my @export_predicates = qw(
16 limit_character_set
17 length_in_range
18 equal_to
19 number_in_range
20 one_of
21 );
22 23 my @export_filters = qw(
23 split_by
24 trim
25 );
26 23 our @EXPORT_OK = (@export_predicates, @export_filters);
27 23 our %EXPORT_TAGS = (
28 validation => \@EXPORT,
29 predicates => \@export_predicates,
30 filters => \@export_filters,
31 all => [ @EXPORT, @export_predicates, @export_filters ],
32 );
33 }
34  
35 # ABSTRACT: A tiny form validator
36  
37 my %coercer = (
38 5 ▶ '+' => sub { (1, '', 0+$_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 4 ▶ '?' => sub { (1, '', length($_[0]) > 0) },
Subroutine __ANON__: called CC=1 SCAR=0.0
40 4 ▶ '?+' => sub { (1, '', !!(0+$_[0])) },
Subroutine __ANON__: called CC=1 SCAR=0.0
41 4 ▶ '?perl' => sub { (1, '', !!$_[0]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
42 3 ▶ '[]' => sub { (1, '', [ _listy($_[0]) ]) },
Subroutine __ANON__: called CC=1 SCAR=0.0
43 18 ▶ '{}' => sub { (1, '', ref $_[0] ? +{ _listy($_[0]) } : { $_[0] => $_[0] }) },
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] ? : 17 1 18
44 23 );
45  
46 1 ▶sub _sub_coercer {
Subroutine _sub_coercer: called CC=1 SCAR=0.0
47 1 my ($sub) = @_;
48 1 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
49 1 local $_ = $_[0];
50 1 my $into = $sub->(@_);
51 1 (1, '', $into);
52 }
53 1 }
54  
55 3 ▶sub _yes_no_coercer {
Subroutine _yes_no_coercer: called CC=1 SCAR=0.0
56 3 my ($yes, $no) = @_;
57 3 my $fcyes = fc $yes;
58 3 my $fcno = fc $no;
59 3 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
60 3 my $fc_ = fc $_[0];
61 3 ▶ my $truth = $fc_ eq $fcyes ? 1
Branch: 2 branches
BranchTrueFalseTotal
$fc_ eq $fcyes ? : 1 2 3
$fc_ eq $fcno ? : 1 1 2
62 : $fc_ eq $fcno ? 0
63 : undef;
64  
65 3 return (defined $truth, qq[Enter "$yes" or "$no".], $truth);
66 3 };
67 }
68  
69 1 ▶sub _package_coercer {
Subroutine _package_coercer: called CC=1 SCAR=0.0
70 1 my ($package) = @_;
71 1 ▶ sub { (1, '', $package->new($_[0])) }
Subroutine __ANON__: called CC=1 SCAR=0.0
72 1 }
73  
74 1 ▶sub _type_coercer {
Subroutine _type_coercer: called CC=1 SCAR=0.0
75 1 my ($type) = @_;
76 1 ▶ sub { (1, '', $type->coerce($_[0])) }
Subroutine __ANON__: called CC=1 SCAR=0.0
77 1 }
78  
79 17 ▶sub _sub_validator {
Subroutine _sub_validator: called CC=1 SCAR=0.0
80 17 my ($sub) = @_;
81 56 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
82 56 ▶ return (1, '', $_[0]) unless defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 1 55 56
83 55 local $_ = $_[0];
84 55 my ($valid, $error) = $sub->(@_);
85 55 ($valid, $error, $_[0]);
86 17 };
87 }
88  
89 6 ▶sub _re_validator {
Subroutine _re_validator: called CC=1 SCAR=0.0
90 6 my ($re) = @_;
91 6 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
92 6 my ($value) = @_;
93 6 ▶ return (1, '', $value) unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 6 6
94 6 my $valid = $value =~ /$re/;
95 6 ($valid, 'Incorrect.', $value);
96 6 };
97 }
98  
99 3 ▶sub _type_validator {
Subroutine _type_validator: called CC=4 SCAR=13.9
100 3 my ($type) = @_;
101 3 ▶ if ($type->can('check')) {
Branch: 2 branches
BranchTrueFalseTotal
if ($type->can('check')) { } 2 1 3
elsif ($type->can('validate')) { } 1 0 1
102 1 ▶ my $message = $type->can('get_message') ? sub { $type->get_message($_[0]) }
Subroutine __ANON__: called CC=1 SCAR=0.0
103 2 ▶ : 'Incorrect.';
Branch: 1 branch
BranchTrueFalseTotal
$type->can('get_message') ? : 1 1 2
104  
105 4 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
106 4 my ($value) = @_;
107 4 ▶ return (1, '', $value) unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 4 4
108 4 my $valid = $type->check($value);
109 4 ($valid, $message, $value);
110 }
111 2 }
112 elsif ($type->can('validate')) {
113 2 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
114 2 my ($value) = @_;
115 2 ▶ return (1, '', $value) unless defined $value;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $value 0 2 2
116 2 my $message = $type->validate($value);
117 2 ▶ (!defined $message, $message//'', $value);
Condition100%2/2
$message // ""
l!l
11
MC/DC100%1/1
$message // ""
$message
Truth table100%2/2
A
A= $message
Aresult
11
00
118 }
119 1 }
120  
121 0 die "bad type encountered"; # uncoverable statement
122 }
123  
124 2 ▶sub _with_error {
Subroutine _with_error: called CC=1 SCAR=0.0
125 2 my ($decl, $with_error) = @_;
126 5 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
127 5 my ($valid, $decl_message, $value) = $decl->(@_);
128 5 ($valid, $with_error, $value);
129 }
130 2 }
131  
132 78 ▶sub _listy {
Subroutine _listy: called CC=3 SCAR=11.0
133 78 my ($stuff) = @_;
134 78 ▶ return @$stuff if 'ARRAY' eq ref $stuff;
Branch: 1 branch
BranchTrueFalseTotal
if "ARRAY" eq ref $stuff 50 28 78
135 28 ▶ return %$stuff if 'HASH' eq ref $stuff;
Branch: 1 branch
BranchTrueFalseTotal
if "HASH" eq ref $stuff 27 1 28
136 1 return ($stuff);
137 }
138  
139 30 ▶sub _ytsil {
Subroutine _ytsil: called CC=3 SCAR=11.4
140 30 my ($old_stuff, $new_stuff) = @_;
141 30 ▶ return $new_stuff if 'ARRAY' eq ref $old_stuff;
Branch: 1 branch
BranchTrueFalseTotal
if "ARRAY" eq ref $old_stuff 15 15 30
142 15 ▶ return { @$new_stuff } if 'HASH' eq ref $old_stuff;
Branch: 1 branch
BranchTrueFalseTotal
if "HASH" eq ref $old_stuff 15 0 15
143 0 return $new_stuff->[0];
144 }
145  
146 6 ▶sub _for_each {
Subroutine _for_each: called CC=4 SCAR=13.9
147 6 my ($element, $decl_sub) = @_;
148  
149 6 ▶ my $lister = $element eq 'each' ? sub { _listy($_[0]) } : sub { pairs(_listy($_[0])) };
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$element eq 'each' ? : 2 4 6
150  
151 6 my ($puller, $pusher);
152 6 ▶ if ($element eq 'key') {
Branch: 2 branches
BranchTrueFalseTotal
if ($element eq 'key') { } 2 4 6
elsif ($element eq 'value') { } 2 2 4
153 2 ▶ $puller = sub { $_[0][0] }; # pull key from pairs()
Subroutine __ANON__: called CC=1 SCAR=0.0
154 2 ▶ $pusher = sub { ($_[1], $_[0][1]) }; # push updated key, original value from pairs()
Subroutine __ANON__: called CC=1 SCAR=0.0
155 }
156 elsif ($element eq 'value') {
157 2 ▶ $puller = sub { $_[0][1] }; # pull value from pairs()
Subroutine __ANON__: called CC=1 SCAR=0.0
158 2 ▶ $pusher = sub { ($_[0][0], $_[1]) }; # push original key from pairs(), updated value
Subroutine __ANON__: called CC=1 SCAR=0.0
159 }
160 else { # $element eq 'each'
161 2 ▶ $puller = sub { $_[0] }; # pull value from _listy()
Subroutine __ANON__: called CC=1 SCAR=0.0
162 2 ▶ $pusher = sub { $_[1] }; # push updated element
Subroutine __ANON__: called CC=1 SCAR=0.0
163 }
164  
165 30 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
166 30 my ($stuff) = @_;
167  
168 30 my $valid = 1;
169 30 my $error = '';
170 my @new_stuff = map {
171 30 my $update_value = $puller->($_);
172 32 my ($element_valid, $element_error, $element_value) = $decl_sub->($update_value);
173 32 ▶ unless ($element_valid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($element_valid) 16 16 32
174 16 $valid = 0;
175 16 ▶ $error ||= $element_error;
Condition66%2/3
$error ||= $element_error
l!l&&r!l&&!r
2140
MC/DC0%0/2
$error ||= $element_error
$error $element_error
Truth table66%2/3
A ||= B
A= $errorB= $element_error
ABresult
1X1
011
000
176 }
177 32 $pusher->($_, $element_value);
178 } $lister->($stuff);
179  
180 30 return ($valid, $error, _ytsil($stuff, \@new_stuff));
181 }
182 6 }
183  
184 # lifted from perldoc perldata
185 23 my $NAME_RE = qr/ (?[ ( \p{Word} & \p{XID_Start} ) + [_] ])
186 (?[ ( \p{Word} & \p{XID_Continue} ) ]) * /x;
187 23 my $PACKAGE_RE = qr/^ $NAME_RE (?: ('|::) $NAME_RE )* $/x;
188  
189 39 ▶sub _locate_package_name {
Subroutine _locate_package_name: called CC=6 SCAR=18.0
190 39 my ($spec_name, $depth) = @_;
191 39 ▶ $depth //= 1;
Condition50%1/2
$depth //= 1
l!l
039
MC/DC0%0/1
$depth //= 1
$depth
Truth table50%1/2
A
A= $depth
Aresult
11
00
192  
193 39 ▶ die "name must be a valid Perl identifier"
Branch: 1 branch
BranchTrueFalseTotal
unless $spec_name =~ /$PACKAGE_RE/u 0 39 39
194 unless $spec_name =~ /$PACKAGE_RE/;
195  
196 39 my ($package, $name);
197 39 ▶ if ($spec_name =~ /\b(::|')\b/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec_name =~ /\b(::|')\b/u) { } 1 38 39
198 1 my @parts = split /::|'/, $spec_name;
199 1 $name = pop @parts;
200 1 $package = join '::', @parts;
201 }
202 else {
203 38 ($package) = caller($depth);
204 38 ▶ $package //='main';
Condition50%1/2
$package //= "main"
l!l
380
MC/DC0%0/1
$package //= "main"
$package
Truth table50%1/2
A
A= $package
Aresult
11
00
205 38 $name = $spec_name;
206 }
207  
208 39 $package .= '::FORM_VALIDATOR_TINY_SPECIFICATION';
209 {
210 23 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
211 39 ▶ ${ $package } //= {};
Condition100%2/2
${$package;} //= {}
l!l
2415
MC/DC100%1/1
${$package;} //= {}
${$package;}
Truth table100%2/2
A
A= ${$package;}
Aresult
11
00
212 }
213  
214 39 ($package, $name);
215 }
216  
217 40 ▶sub validation_spec($;$) {
Subroutine validation_spec: called CC=36 SCAR=35.8
Pod documented
218 40 my ($name, $spec) = @_;
219 40 ▶ if (ref $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $name) 23 17 40
220 23 $spec = $name;
221 23 undef $name;
222 }
223  
224 40 my $error;
225 40 ▶ if (defined $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $name) { } 17 23 40
226 17 ▶ $error = sub { die "spec [$name] ", @_ };
Subroutine __ANON__: called CC=1 SCAR=0.0
227 }
228 else {
229 23 ▶ if (!defined wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined wantarray) 1 22 23
230 1 die "useless call to validation_spec with no name in void context";
231 }
232 22 ▶ $error = sub { die "spec ", @_ };
Subroutine __ANON__: called CC=1 SCAR=0.0
233 }
234  
235 39 ▶ $error->("must be an array reference")
Branch: 1 branch
BranchTrueFalseTotal
unless "ARRAY" eq ref $spec 1 38 39
236 unless 'ARRAY' eq ref $spec;
237  
238 38 ▶ $error->("contains odd number of elements")
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$spec % 2 == 0 1 37 38
239 unless scalar @$spec % 2 == 0;
240  
241 37 my @decl_spec;
242 my %encountered_fields;
243 37 for my $field_pair (pairs @$spec) {
244 58 my ($field, $decls) = @$field_pair;
245  
246 58 ▶ my $error = sub { $error->("input declaration for [$field] ", @_) };
Subroutine __ANON__: called CC=1 SCAR=0.0
247  
248 58 ▶ $error->("has been defined twice") if $encountered_fields{ $field };
Branch: 1 branch
BranchTrueFalseTotal
if $encountered_fields{$field} 1 57 58
249 57 $encountered_fields{ $field }++;
250  
251 57 ▶ $error->("must be in an array reference")
Branch: 1 branch
BranchTrueFalseTotal
unless "ARRAY" eq ref $decls 1 56 57
252 unless 'ARRAY' eq ref $decls;
253  
254 56 ▶ $error->("contains odd number of elements")
Branch: 1 branch
BranchTrueFalseTotal
unless scalar @$decls % 2 == 0 1 55 56
255 unless scalar @$decls % 2 == 0;
256  
257 55 my %options;
258 55 my @decl = (\%options);
259 55 for my $decl_pair (pairs @$decls) {
260 82 my ($op, $arg) = @$decl_pair;
261  
262 82 ▶ if (any { $op eq $_ } qw( from multiple trim )) {
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 5 branches
BranchTrueFalseTotal
if (&any(sub { $op eq $_; } , 'from', 'multiple', 'trim')) { } 17 65 82
elsif ($op =~ /^ (?: (each|key|value)_ )? into $/ux) { } 24 41 65
elsif ($op eq 'required' or $op eq 'optional') { } 6 35 41
elsif ($op =~ /^ (?: (each|key|value)_ )? must $/ux) { } 31 4 35
elsif ($op eq 'with_error') { } 3 1 4
263 17 ▶ $error->("found [$op] after filter or validation declarations")
Branch: 1 branch
BranchTrueFalseTotal
if @decl > 1 3 14 17
264 if @decl > 1;
265  
266 $error->("has more than one [$op] declaration")
267 14 ▶ if defined $options{ $op };
Branch: 1 branch
BranchTrueFalseTotal
if defined $options{$op} 3 11 14
268  
269 11 $options{ $op } = $arg;
270 }
271  
272 elsif ($op =~ /^ (?: (each|key|value)_ )? into $/x) {
273 24 my $element = $1;
274  
275 24 my $into_sub;
276 24 ▶ if ('CODE' eq ref $arg) {
Branch: 5 branches
BranchTrueFalseTotal
if ('CODE' eq ref $arg) { } 1 23 24
elsif (builtin::blessed($arg) and $arg->can('coerce')) { } 1 22 23
elsif (defined $coercer{$arg}) { } 14 8 22
elsif ($arg =~ /\?([^!]+)!(.+)/u) { } 3 5 8
elsif ($arg =~ /$PACKAGE_RE/u) { } 1 4 5
277 1 $into_sub = _sub_coercer($arg);
278 }
279 ▶ elsif (blessed $arg && $arg->can('coerce')) {
Condition66%2/3
builtin::blessed($arg) and $arg->can("coerce")
!ll&&!rl&&r
2201
MC/DC50%1/2
builtin::blessed($arg) and $arg->can("coerce")
builtin::blessed($arg) $arg->can("coerce")
Truth table66%2/3
A and B
A= builtin::blessed($arg)B= $arg->can("coerce")
ABresult
0X0
100
111
280 1 $into_sub = _type_coercer($arg);
281 }
282 elsif (defined $coercer{ $arg }) {
283 14 $into_sub = $coercer{ $arg };
284 }
285 elsif ($arg =~ /\?([^!]+)!(.+)/) {
286 3 $into_sub = _yes_no_coercer($1, $2);
287 }
288 elsif ($arg =~ $PACKAGE_RE) {
289 1 $into_sub = _package_coercer($arg);
290 }
291 else {
292 4 $error->("has unknown [$op] declaration argument [$arg]");
293 }
294  
295 20 ▶ $into_sub = _for_each($element, $into_sub) if $element;
Branch: 1 branch
BranchTrueFalseTotal
if $element 0 20 20
296 20 push @decl, $into_sub;
297 }
298  
299 ▶ elsif ($op eq 'required' || $op eq 'optional') {
Condition100%3/3
$op eq "required" or $op eq "optional"
l!l&&r!l&&!r
3335
MC/DC100%2/2
$op eq "required" or $op eq "optional"
$op eq "required" $op eq "optional"
Truth table100%3/3
A or B
A= $op eq "required"B= $op eq "optional"
ABresult
1X1
011
000
300 6 ▶ $arg = !$arg if $op eq 'optional';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "optional" 3 3 6
301  
302 # Validate on required
303 6 ▶ if ($arg) {
Branch: 1 branch
BranchTrueFalseTotal
if ($arg) { } 3 3 6
304 10 ▶ push @decl, sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
305 10 ▶ my $valid = (defined $_[0] && $_[0] =~ /./);
Condition66%2/3
defined $_[0] && $_[0] =~ /./u
!ll&&!rl&&r
406
MC/DC50%1/2
defined $_[0] && $_[0] =~ /./u
defined $_[0] $_[0] =~ /./u
Truth table66%2/3
A && B
A= defined $_[0]B= $_[0] =~ /./u
ABresult
0X0
100
111
306 10 ($valid, 'Required.', $_[0])
307 3 };
308 }
309  
310 # Shortcircuit on optional
311 else {
312 10 ▶ push @decl, sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
313 10 ▶ my $valid = (defined $_[0] && $_[0] =~ /./) ? 1 : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] && $_[0] =~ /./u ? : 8 2 10
Condition66%2/3
defined $_[0] and $_[0] =~ /./u
!ll&&!rl&&r
208
MC/DC50%1/2
defined $_[0] and $_[0] =~ /./u
defined $_[0] $_[0] =~ /./u
Truth table66%2/3
A and B
A= defined $_[0]B= $_[0] =~ /./u
ABresult
0X0
100
111
314 10 ($valid, '', $_[0])
315 3 };
316 }
317 }
318  
319 elsif ($op =~ /^ (?: (each|key|value)_ )? must $/x) {
320 31 my $element = $1;
321  
322 31 my $must_sub;
323 31 ▶ if ('CODE' eq ref $arg) {
Branch: 3 branches
BranchTrueFalseTotal
if ('CODE' eq ref $arg) { } 17 14 31
elsif ('Regexp' eq ref $arg) { } 6 8 14
elsif (builtin::blessed($arg) and $arg->can('check') || $arg->can('validate')) { } 3 5 8
324 17 $must_sub = _sub_validator($arg);
325 }
326 elsif ('Regexp' eq ref $arg) {
327 6 $must_sub = _re_validator($arg);
328 }
329 ▶ elsif (blessed $arg && ($arg->can('check') || $arg->can('validate'))) {
Condition100%6/6
builtin::blessed($arg) and $arg->can("check") || $arg->can("validate")
!ll&&!rl&&r
413
$arg->can("check") or $arg->can("validate")
l!l&&r!l&&!r
211
MC/DC100%3/3
builtin::blessed($arg) and $arg->can("check") || $arg->can("validate")
builtin::blessed($arg) $arg->can("check") $arg->can("validate")
Truth table100%4/4
A and B or C
A= builtin::blessed($arg)B= $arg->can("check")C= $arg->can("validate")
ABCresult
0XX0
1000
11X1
1011
330 3 $must_sub = _type_validator($arg);
331 }
332 else {
333 5 $error->("has unknown [$op] declaration argument [$arg]");
334 }
335  
336 26 ▶ $must_sub = _for_each($element, $must_sub) if $element;
Branch: 1 branch
BranchTrueFalseTotal
if $element 6 20 26
337 26 push @decl, $must_sub;
338 }
339  
340 elsif ($op eq 'with_error') {
341 3 ▶ $error->("has [$op] before a declaration in which it may modify")
Branch: 1 branch
BranchTrueFalseTotal
unless @decl > 1 1 2 3
342 unless @decl > 1;
343  
344 2 my $last_decl = pop @decl;
345 2 push @decl, _with_error($last_decl, $arg);
346 }
347  
348 else {
349 1 $error->("has unknown [$op]");
350 }
351 }
352  
353 38 push @decl_spec, $field, \@decl;
354 }
355  
356 17 my $finished_spec = \@decl_spec;
357 17 bless $finished_spec, __PACKAGE__;
358  
359 17 ▶ if (defined $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $name) 16 1 17
360 16 my $package;
361 16 ($package, $name) = _locate_package_name($name);
362  
363 {
364 23 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
365 16 ${ $package }->{ $name } = $finished_spec;
366 }
367 }
368  
369 17 return $finished_spec;
370 }
371  
372 28 ▶sub validate_form($$) {
Subroutine validate_form: called CC=19 SCAR=29.9
Pod documented
373 28 my ($name, $input) = @_;
374 28 my @input;
375 28 ▶ if (blessed $input && $input->can('flatten')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($input) and $input->can('flatten')) { } 0 28 28
Condition33%1/3
builtin::blessed($input) and $input->can("flatten")
!ll&&!rl&&r
2800
MC/DC0%0/2
builtin::blessed($input) and $input->can("flatten")
builtin::blessed($input) $input->can("flatten")
Truth table33%1/3
A and B
A= builtin::blessed($input)B= $input->can("flatten")
ABresult
0X0
100
111
376 0 @input = $input->flatten;
377 }
378 else {
379 28 @input = _listy($input);
380 }
381  
382 28 my $spec = $name;
383 28 ▶ unless (blessed $spec && $spec->isa(__PACKAGE__)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($spec) and $spec->isa(__PACKAGE__)) 23 5 28
Condition66%2/3
builtin::blessed($spec) and $spec->isa(__PACKAGE__)
!ll&&!rl&&r
2305
MC/DC50%1/2
builtin::blessed($spec) and $spec->isa(__PACKAGE__)
builtin::blessed($spec) $spec->isa(__PACKAGE__)
Truth table66%2/3
A and B
A= builtin::blessed($spec)B= $spec->isa(__PACKAGE__)
ABresult
0X0
100
111
384 23 my $package;
385 23 ($package, $name) = _locate_package_name($name);
386  
387 {
388 23 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
389 23 $spec = ${ $package }->{ $name };
390  
391 23 ▶ die "no spec with name [$name] found in package [$package]"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec 0 23 23
392 unless defined $spec;
393 }
394 }
395  
396 28 ▶ die "no spec provided to validate with" unless defined $spec;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec 0 28 28
397  
398 28 my (%params, %errors);
399 28 FIELD: for my $field_pair (pairs @$spec) {
400 91 my ($field, $decls) = @$field_pair;
401  
402 91 my $field_input;
403 91 DECL_FOR_FIELD: for my $decl (@$decls) {
404 221 ▶ if ('HASH' eq ref $decl) {
Branch: 1 branch
BranchTrueFalseTotal
if ('HASH' eq ref $decl) { } 91 130 221
405 91 ▶ my $from = $decl->{from} // $field;
Condition33%1/3
$decl->{"from"} // $field
l!l&&r!l&&!r
0910
MC/DC0%0/2
$decl->{"from"} // $field
$decl->{"from"} $field
Truth table33%1/3
A // B
A= $decl->{"from"}B= $field
ABresult
1X1
011
000
406 91 ▶ my $multiple = $decl->{multiple} // 0;
Condition100%2/2
$decl->{"multiple"} // 0
l!l
3259
MC/DC100%1/1
$decl->{"multiple"} // 0
$decl->{"multiple"}
Truth table100%2/2
A
A= $decl->{"multiple"}
Aresult
11
00
407 91 ▶ my $trim = $decl->{trim} // 1;
Condition50%1/2
$decl->{"trim"} // 1
l!l
091
MC/DC0%0/1
$decl->{"trim"} // 1
$decl->{"trim"}
Truth table50%1/2
A
A= $decl->{"trim"}
Aresult
11
00
408  
409 91 ▶ my @values = pairmap { $b } pairgrep { $a eq $from } @input;
Subroutine __ANON__: called CC=1 SCAR=0.0
Subroutine __ANON__: called CC=1 SCAR=0.0
410 91 ▶ @values = map { if (defined) { s/^\s+//; s/\s+$// } $_ } @values if $trim;
Branch: 2 branches
BranchTrueFalseTotal
if $trim 91 0 91
if (defined $_) 104 4 108
411  
412 91 ▶ if ($multiple) {
Branch: 1 branch
BranchTrueFalseTotal
if ($multiple) { } 32 59 91
413 32 $field_input = \@values;
414 }
415 else {
416 59 $field_input = pop @values;
417 }
418 }
419  
420 else {
421 130 my ($valid, $error, $new_value) = $decl->($field_input, \%params);
422  
423 130 ▶ if (!defined $valid) {
Branch: 2 branches
BranchTrueFalseTotal
if (not defined $valid) { } 2 128 130
elsif ($valid) { } 97 31 128
424 2 $field_input = undef;
425 2 last DECL_FOR_FIELD;
426 }
427 elsif ($valid) {
428 97 $field_input = $new_value;
429 }
430 else {
431 31 $field_input = undef;
432 31 push @{ $errors{ $field } }, $error;
433 31 last DECL_FOR_FIELD;
434 }
435 }
436 }
437  
438 91 $params{ $field } = $field_input;
439 }
440  
441 28 ▶ my $errors = scalar keys %errors ? \%errors : undef;
Branch: 1 branch
BranchTrueFalseTotal
scalar keys %errors ? : 12 16 28
442 28 return (\%params, $errors);
443 }
444  
445 10 ▶sub _comma_and {
Subroutine _comma_and: called CC=4 SCAR=14.0
446 10 ▶ if (@_ == 0) {
Branch: 3 branches
BranchTrueFalseTotal
if (@_ == 0) { } 0 10 10
elsif (@_ == 1) { } 5 5 10
elsif (@_ == 2) { } 2 3 5
447 0 return '';
448 }
449 elsif (@_ == 1) {
450 5 return $_[0];
451 }
452 elsif (@_ == 2) {
453 2 return "$_[0] and $_[1]";
454 }
455 else {
456 3 my $last = pop @_;
457 3 return join(", ", @_) . ", and " . $last
458 }
459 }
460  
461 11 ▶sub limit_character_set {
Subroutine limit_character_set: called CC=4 SCAR=13.9
Pod documented
462 13 ▶ my $_build_class = sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
463 my @class_parts = map {
464 13 ▶ if (1 == length $_) {
Branch: 3 branches
BranchTrueFalseTotal
if (1 == length $_) { } 2 18 20
elsif (/^(.)-(.)$/u and ord $1 < ord $2) { } 13 5 18
elsif (/^\[([^\]]+)\]$/u) { } 1 4 5
465 2 [ "[$_]", qq["$_"] ]
466 }
467 ▶ elsif (/^(.)-(.)$/ && ord($1) < ord($2)) {
Condition100%3/3
/^(.)-(.)$/u and ord $1 < ord $2
!ll&&!rl&&r
4113
MC/DC100%2/2
/^(.)-(.)$/u and ord $1 < ord $2
/^(.)-(.)$/u ord $1 < ord $2
Truth table100%3/3
A and B
A= /^(.)-(.)$/uB= ord $1 < ord $2
ABresult
0X0
100
111
468 13 [ "[$_]", qq["$1" through "$2"] ]
469 }
470 elsif (/^\[([^\]]+)\]$/) {
471 1 my $name = my $prop = $1;
472 1 $name =~ s/_/ /g;
473 1 [ "\\p{$prop}", qq[\L$name\E characters] ]
474 }
475 else {
476 4 die "invalid character set [$_]";
477 }
478 } @_;
479  
480 9 my $classes = join ' + ', map { $_->[0] } @class_parts;
481 9 my $re = qr/(?[ $classes ])/x;
482  
483 9 my $error = _comma_and(map { $_->[1] } @class_parts);
484  
485 9 return ($re, $error);
486 11 };
487  
488 11 ▶ if (@_ == 2 && 'ARRAY' eq ref $_[0] && 'ARRAY' eq ref $_[1]) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2 and 'ARRAY' eq ref $_[0] and 'ARRAY' eq ref $_[1]) { } 3 8 11
Condition83%5/6
@_ == 2 and "ARRAY" eq ref $_[0] and "ARRAY" eq ref $_[1]
!ll&&!rl&&r
803
@_ == 2 and "ARRAY" eq ref $_[0]
!ll&&!rl&&r
623
MC/DC66%2/3
@_ == 2 and "ARRAY" eq ref $_[0] and "ARRAY" eq ref $_[1]
@_ == 2 "ARRAY" eq ref $_[0] "ARRAY" eq ref $_[1]
Truth table75%3/4
A and B and C
A= @_ == 2B= "ARRAY" eq ref $_[0]C= "ARRAY" eq ref $_[1]
ABCresult
0XX0
10X0
1100
1111
489 3 my ($first_re, $first_error) = $_build_class->(@{ $_[0] });
490 2 my ($rest_re, $rest_error) = $_build_class->(@{ $_[1] });
491  
492 1 my $error = "First character only permits: "
493 . $first_error . ". Remaining only permits: "
494 . $rest_error;
495  
496 3 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
497 3 my ($value) = @_;
498 3 my $valid = ($value =~ /^(?:$first_re$rest_re*)?$/);
499 3 ($valid, $error);
500 1 };
501 }
502 else {
503 8 my ($re, $error) = $_build_class->(@_);
504  
505 6 $error = "Only permits: "
506 . $error;
507  
508 12 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
509 12 my ($value) = @_;
510 12 my $valid = ($value =~ /^$re*$/);
511 12 ($valid, $error);
512 6 };
513 }
514 }
515  
516 9 ▶sub length_in_range {
Subroutine length_in_range: called CC=10 SCAR=23.0
Pod documented
517 9 my ($start, $stop) = @_;
518  
519 9 ▶ die "minimum length in length_in_range must be a positive integer, got [$start] instead"
Branch: 1 branch
BranchTrueFalseTotal
unless $start =~ /^(?:[0-9]+|\*)$/u 2 7 9
520 unless $start =~ /^(?:[0-9]+|\*)$/;
521  
522 7 ▶ die "maximum length in length_in_range must be a positive integer, got [$stop] instead"
Branch: 1 branch
BranchTrueFalseTotal
unless $stop =~ /^(?:[0-9]+|\*)$/u 1 6 7
523 unless $stop =~ /^(?:[0-9]+|\*)$/;
524  
525 6 ▶ die "minimum length must be less than or equal to maximum length in length_in_range, got [$start>$stop] instead"
Branch: 1 branch
BranchTrueFalseTotal
if $start ne "*" and $stop ne "*" and $start > $stop 1 5 6
Condition100%6/6
$start ne "*" and $stop ne "*" and $start > $stop
!ll&&!rl&&r
321
$start ne "*" and $stop ne "*"
!ll&&!rl&&r
213
MC/DC100%3/3
$start ne "*" and $stop ne "*" and $start > $stop
$start ne "*" $stop ne "*" $start > $stop
Truth table100%4/4
A and B and C
A= $start ne "*"B= $stop ne "*"C= $start > $stop
ABCresult
0XX0
10X0
1100
1111
526 if $start ne '*' && $stop ne '*' && $start > $stop;
527  
528 5 ▶ if ($start eq '*' && $stop eq '*') {
Branch: 3 branches
BranchTrueFalseTotal
if ($start eq '*' and $stop eq '*') { } 1 4 5
elsif ($start eq '*') { } 1 3 4
elsif ($stop eq '*') { } 1 2 3
Condition100%3/3
$start eq "*" and $stop eq "*"
!ll&&!rl&&r
311
MC/DC100%2/2
$start eq "*" and $stop eq "*"
$start eq "*" $stop eq "*"
Truth table100%3/3
A and B
A= $start eq "*"B= $stop eq "*"
ABresult
0X0
100
111
529 1 ▶ return sub { (1, '') };
Subroutine __ANON__: called CC=1 SCAR=0.0
530 }
531 elsif ($start eq '*') {
532 3 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
533 3 my $valid = length $_[0] <= $stop;
534 3 ($valid, "Must be no longer than $stop characters.")
535 1 };
536 }
537 elsif ($stop eq '*') {
538 3 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
539 3 my $valid = length $_[0] >= $start;
540 3 ($valid, "Must be at least $start characters long.")
541 }
542 1 }
543 else {
544 5 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
545 5 ▶ return (1, '') unless defined $_[0];
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_[0] 0 5 5
546 5 ▶ if (length $_[0] >= $start) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $_[0] >= $start) { } 4 1 5
547 4 my $valid = length $_[0] <= $stop;
548 4 return ($valid, "Must be no longer than $stop characters.");
549 }
550 else {
551 1 return ('', "Must be at least $start characters in length.")
552 }
553 }
554 2 }
555 }
556  
557 1 ▶sub equal_to {
Subroutine equal_to: called CC=1 SCAR=0.0
Pod documented
558 1 my ($field_name) = @_;
559  
560 2 ▶ sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
561 2 ($_[0] eq $_[1]{ $field_name }, "The value must match $field_name.")
562 }
563 1 }
564  
565 9 ▶sub number_in_range {
Subroutine number_in_range: called CC=16 SCAR=27.7
Pod documented
566 9 my $start = shift;
567 9 my $stop = shift;
568 9 my $starti = 1;
569 9 my $stopi = 1;
570  
571 9 ▶ if ($start eq 'exclusive') {
Branch: 1 branch
BranchTrueFalseTotal
if ($start eq "exclusive") 1 8 9
572 1 $starti = 0;
573 1 $start = $stop;
574 1 $stop = shift;
575 }
576  
577 9 ▶ if ($stop eq 'exclusive') {
Branch: 1 branch
BranchTrueFalseTotal
if ($stop eq "exclusive") 1 8 9
578 1 $stopi = 0;
579 1 $stop = shift;
580 }
581  
582 9 ▶ die "minimum length in length_in_range must be a positive integer, got [$start] instead"
Branch: 1 branch
BranchTrueFalseTotal
unless $start eq "*" or &looks_like_number($start) 1 8 9
Condition100%3/3
$start eq "*" or &looks_like_number($start)
l!l&&r!l&&!r
261
MC/DC100%2/2
$start eq "*" or &looks_like_number($start)
$start eq "*" &looks_like_number($start)
Truth table100%3/3
A or B
A= $start eq "*"B= &looks_like_number($start)
ABresult
1X1
011
000
583 unless $start eq '*' || looks_like_number($start);
584  
585 8 ▶ die "maximum length in length_in_range must be a positive integer, got [$stop] instead"
Branch: 1 branch
BranchTrueFalseTotal
unless $stop eq "*" or &looks_like_number($stop) 1 7 8
Condition100%3/3
$stop eq "*" or &looks_like_number($stop)
l!l&&r!l&&!r
341
MC/DC100%2/2
$stop eq "*" or &looks_like_number($stop)
$stop eq "*" &looks_like_number($stop)
Truth table100%3/3
A or B
A= $stop eq "*"B= &looks_like_number($stop)
ABresult
1X1
011
000
586 unless $stop eq '*' || looks_like_number($stop);
587  
588 7 ▶ die "minimum length must be less than or equal to maximum length in length_in_range, got [$start>$stop] instead"
Branch: 1 branch
BranchTrueFalseTotal
if $start ne "*" and $stop ne "*" and $start > $stop 1 6 7
Condition100%6/6
$start ne "*" and $stop ne "*" and $start > $stop
!ll&&!rl&&r
421
$start ne "*" and $stop ne "*"
!ll&&!rl&&r
223
MC/DC100%3/3
$start ne "*" and $stop ne "*" and $start > $stop
$start ne "*" $stop ne "*" $start > $stop
Truth table100%4/4
A and B and C
A= $start ne "*"B= $stop ne "*"C= $start > $stop
ABCresult
0XX0
10X0
1100
1111
589 if $start ne '*' && $stop ne '*' && $start > $stop;
590  
591 12 ▶ my $check_start = $starti ? sub { (($_[0] >= $start), "Number must be at least $start.") }
Subroutine __ANON__: called CC=1 SCAR=0.0
592 6 ▶ : sub { (($_[0] > $start), "Number must be greater than $start.") };
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$starti ? : 5 1 6
593 7 ▶ my $check_stop = $stopi ? sub { (($_[0] <= $stop), "Number must be no more than $stop.") }
Subroutine __ANON__: called CC=1 SCAR=0.0
594 6 ▶ : sub { (($_[0] < $stop), "Number must be less than $stop.") };
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
$stopi ? : 5 1 6
595  
596 6 ▶ if ($start eq '*' && $stop eq '*') {
Branch: 3 branches
BranchTrueFalseTotal
if ($start eq '*' and $stop eq '*') { } 1 5 6
elsif ($start eq '*') { } 1 4 5
elsif ($stop eq '*') { } 2 2 4
Condition100%3/3
$start eq "*" and $stop eq "*"
!ll&&!rl&&r
411
MC/DC100%2/2
$start eq "*" and $stop eq "*"
$start eq "*" $stop eq "*"
Truth table100%3/3
A and B
A= $start eq "*"B= $stop eq "*"
ABresult
0X0
100
111
597 1 ▶ return sub { (1, '') };
Subroutine __ANON__: called CC=1 SCAR=0.0
598 }
599 elsif ($start eq '*') {
600 1 return $check_stop;
601 }
602 elsif ($stop eq '*') {
603 2 return $check_start;
604 }
605 else {
606 7 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
607 7 my ($v, $e) = $check_start->(@_);
608 7 ▶ return ($v, $e) unless $v;
Branch: 1 branch
BranchTrueFalseTotal
unless $v 2 5 7
609 5 return $check_stop->(@_);
610 }
611 2 }
612 }
613  
614 2 ▶sub one_of {
Subroutine one_of: called CC=2 SCAR=6.9
Pod documented
615 2 ▶ die "at least one value must be provided to one_of"
Branch: 1 branch
BranchTrueFalseTotal
unless @_ > 0 1 1 2
616 unless @_ > 0;
617  
618 1 my @enum = @_;
619 4 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
620 4 my ($value) = @_;
621 4 for my $allowed (@enum) {
622 9 ▶ return (1, '') if $value eq $allowed;
Branch: 1 branch
BranchTrueFalseTotal
if $value eq $allowed 3 6 9
623 }
624  
625 return (0, 'Must be one of: '
626 1 . _comma_and( map { qq["$_"] } @enum )
627 );
628 1 };
629 }
630  
631 4 ▶sub split_by {
Subroutine split_by: called CC=5 SCAR=16.1
Pod documented
632 4 my ($by, $count) = @_;
633  
634 4 ▶ die "missing string or regex to split by"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $by 1 3 4
635 unless defined $by;
636  
637 3 ▶ die "count must be greater than 1 if present"
Branch: 1 branch
BranchTrueFalseTotal
if defined $count and $count <= 1 1 2 3
Condition100%3/3
defined $count and $count <= 1
!ll&&!rl&&r
111
MC/DC100%2/2
defined $count and $count <= 1
defined $count $count <= 1
Truth table100%3/3
A and B
A= defined $countB= $count <= 1
ABresult
0X0
100
111
638 if defined $count && $count <= 1;
639  
640 2 ▶ if ($count) {
Branch: 1 branch
BranchTrueFalseTotal
if ($count) { } 1 1 2
641 1 ▶ sub { defined $_[0] ? [ split $by, $_[0], $count ] : [] }
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 1 0 1
642 1 }
643 else {
644 1 ▶ sub { defined $_[0] ? [ split $by, $_[0] ] : [] }
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
defined $_[0] ? : 1 0 1
645 1 }
646 }
647  
648 5 ▶sub trim {
Subroutine trim: called CC=5 SCAR=16.2
Pod documented
649 5 ▶ my $only = shift // 'both';
Condition100%2/2
shift() // "both"
l!l
41
MC/DC100%1/1
shift() // "both"
shift()
Truth table100%2/2
A
A= shift()
Aresult
11
00
650 5 ▶ if ($only eq 'both') {
Branch: 3 branches
BranchTrueFalseTotal
if ($only eq 'both') { } 2 3 5
elsif ($only eq 'left') { } 1 2 3
elsif ($only eq 'right') { } 1 1 2
651 2 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
652 2 ▶ return unless defined $_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 0 2 2
653 2 s/\A\s+//;
654 2 s/\s+\Z//r;
655 2 };
656 }
657 elsif ($only eq 'left') {
658 1 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
659 1 ▶ return unless defined $_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 0 1 1
660 1 s/\A\s+//r;
661 }
662 1 }
663 elsif ($only eq 'right') {
664 1 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
665 1 ▶ return unless defined $_;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $_ 0 1 1
666 1 s/\s+\Z//r;
667 }
668 1 }
669 else {
670 1 die qq[unknown trim option [$only], expected "both" or "left" or "right"];
671 }
672 }
673  
674 23 1;
675  
676 =pod
677  
678 =encoding UTF-8
679  
680 =head1 NAME
681  
682 FormValidator::Tiny - A tiny form validator
683  
684 =head1 VERSION
685  
686 version 0.004
687  
688 =head1 SYNOPSIS
689  
690 use FormValidator::Tiny qw( :validation :predicates :filtesr );
691 use Email::Valid; # <-- for demonstration, not required
692 use Email::Address; # <-- for demonstration, not required
693 use Types::Standard qw( Int ); # <-- for demonstration, not required
694  
695 validation_spec edit_user => [
696 login_name => [
697 required => 1,
698 must => limit_character_set('_', 'a-z', 'A-Z', '0-9'),
699 must => length_in_range(5, 16),
700 ],
701 name => [
702 required => 1,
703 must => length_in_range(1, 100),
704 ],
705 age => [
706 optional => 1,
707 into => '+',
708 must => Int,
709 must => number_in_range(13, '*'),
710 ],
711 password => [
712 required => 1,
713 must => length_in_range(8, 72),
714 ],
715 confirm_password => [
716 required => 1,
717 must => equal_to('password'),
718 ],
719 email => [
720 required => 1,
721 must => length_in_range(5, 250),
722 must => sub { (
723 !!Email::Valid->address($_),
724 "That is not a well-formed email address."
725 ) },
726 into => 'Email::Address',
727 ],
728 groups => [
729 optional => 1,
730 into => split_by(' '),
731 into => '[]',
732 each_must => length_in_range(3, 20),
733 each_must => limit_character_set(
734 ['_', 'a-z', 'A-Z'],
735 ['_', '-', 'a-z', 'A-Z', '0-9'],
736 ),
737 ],
738 tags => [
739 optional => 1,
740 into => split_by(/\s*,\s*/),
741 each_into => split_by(/\s\*:\s*/, 2),
742 into => '{}',
743 key_must => length_in_range(3, 20),
744 key_must => qr/^(?:[A-Z][a-z0-9]*)(?:-[A-Z][a-z0-9]*)*)$/,
745 with_error => 'Tags keys must be of a form like "Favorite" or "Welcome-Message".',
746 value_must => length_in_range(1, 500),
747 value_must => limit_character_set('_', '-', 'a-z', 'A-Z', '0-9'),
748 ],
749 ];
750  
751 # Somehow your web framework gets you a set of form parameters submitted by
752 # POST or whatever. GO!
753 my $params = web_framework_params_method();
754 my ($parsed_params, $errors) = validate_form edit_user => $params;
755  
756 # You probably want better error handling
757 if ($errors) {
758 for my $field (keys %$errors) {
759 print "Error in $field: $_\n" for @{ $errors->{$field} };
760 }
761 }
762  
763 # Form fields are valid, take action!
764 else {
765 do_the_thing(%$parased_params);
766 }
767  
768 =head1 DESCRIPTION
769  
770 The API of this module is still under development and could change, but probably won't.
771  
772 There are lots for form validators, but this one aims to be the one that just
773 does one thing and does it well without involving anything else if it can. If you
774 just need a small form validator without installing all of CPAN, this will do
775 that. If you want to install all of CPAN and use a readable form validation spec
776 syntax, I hope this will do that too.
777  
778 This module requires Perl 5.18 or better as of this writing.
779  
780 =head1 EXPORTS
781  
782 This module exports three sets of functions, each with their own export tag:
783  
784 =over
785  
786 =item :validation
787  
788 This is exported by default. It includes the two central functions provided by this interface, C<validation_spec> and C<validate_form>.
789  
790 =item :predicates
791  
792 This includes the built-in predicate helpers, used with C<must> and C<must>-like directives.
793  
794 =over
795  
796 =item limit_character_set
797  
798 =item length_in_range
799  
800 =item equal_to
801  
802 =item number_in_range
803  
804 =item one_of
805  
806 =back
807  
808 =item :filters
809  
810 This includes the build-in filter helpers, used with C<into> and C<into>-like directives.
811  
812 =over
813  
814 =item split_by
815  
816 =item trim
817  
818 =back
819  
820 =item :all
821  
822 All of the above.
823  
824 =back
825  
826 =head1 FUNCTIONS
827  
828 =head2 validation_spec
829  
830 validation_spec $spec_name => \@spec;
831  
832 This defines a validation specification. It associates a specification named
833 C<$spec_name> with the current package. Any use of C<validate_form> within the
834 current package will use specifications named within the current package. The
835 following example would work fine as the "edit" spec defined in each controller
836 is in their respective package namespaces.
837  
838 package MyApp::Controller::User;
839 validation_spec edit => [ ... ];
840 sub process_edits {
841 my ($self, $c) = @_;
842 my ($p, $e) = validate_form edit => $c->req->body_parameters;
843 ...
844 }
845  
846 package MyApp::Controller::Page;
847 validation_spec edit => [ ... ];
848 sub process_edits {
849 my ($self, $c) = @_;
850 my ($p, $e) = validate_form edit => $c->req->body_parameters;
851 ...
852 }
853  
854 If you want to define them into a different package, name the package as part of
855 the spec. Similarly, you can validate_form using a spec defined in a different
856 package by naming the package when calling L</validate_form>:
857  
858 package MyApp::Forms;
859 validation_spec MyApp::Controller::User::edit => [ ... ];
860  
861 package MyApp::Controller::User;
862 sub process_groups {
863 my ($self, $c) = @_;
864 my ($p, $e) = validate_form MyApp::Controller::UserGroup::edit => $c->req->body_parameters;
865 ...
866 }
867  
868 You can also define your validation specification as lexical variables instead:
869  
870 my $spec = validation_spec [ ... ];
871 my ($p, $e) = validate_form $spec, $c->req->body_parameters;
872  
873 For information about how to craft a spec, see the L</VALIDATION SPECIFICATIONS>
874 section.
875  
876 =head2 validate_form
877  
878 my ($params, $errors) = validate_form $spec, $input_parameters;
879  
880 Compares the given parameters against the named spec. The C<$input_parameters>
881 may be provided as either a hash or an array of alternating key-value pairs. All
882 keys and values must be provided as strings.
883  
884 The method returns two values. The first, C<$params>, is the parameters as far
885 as they have been validated so far. The second, C<$errors> is the errors that
886 have been detected.
887  
888 The C<$params> will be provided as a hash. The keys of this hash will match the
889 keys given in the spec. Some keys may be missing if the provided
890 C<$input_parameters> did not contain values or those values are invalid.
891  
892 If there are no errors, the C<$errors> value will be set to C<undef>. With
893 errors, this will be hash of arrays. The keys of the hash will also match the
894 keys in the spec. Only fields with a validation error will be set. Each value
895 is an array of strings, with each string being an error message describing a
896 validation failure.
897  
898 =head2 limit_character_set
899  
900 must => limit_character_set(@sets)
901 must => limit_character_set(\@fc_sets, \@rc_sets);
902  
903 This returns a subroutine that limits the allowed characters for an input. In
904 the first form, the character set limits are applied to all characters in the
905 value. In the second, the first array limits the characters permitted for the
906 first character and the second limits the characters permitted for the rest.
907  
908 Character sets may be provided as single letters (e.g., "_"), as named unicode
909 character properties wrapped in square brackets (e.g., "[Uppercase_Letter]"), or
910 as ranges connected by a hyphen (e.g., "a-z").
911  
912 =head2 length_in_range
913  
914 must => length_in_range('*', 10)
915 must => length_in_range(10, '*')
916 must => length_in_range(10, 100)
917  
918 This returns a subroutine for use with C<must> declarations that asserts the
919 minimum and maximum string character length permitted for a value. Use an
920 asterisk to define no limit.
921  
922 =head2 equal_to
923  
924 must => equal_to('field')
925  
926 This returns a subroutine for use with C<must> declarations that asserts that
927 the value must be exactly equal to another field in the input.
928  
929 =head2 number_in_range
930  
931 must => number_in_range('*', 100)
932 must => number_in_range(100, '*')
933 must => number_in_range(100, 500)
934 must => number_in_range(exclusive => 100, exclusive => 500)
935  
936 Returns a predicate for must that requires the integer to be within the given
937 range. The endpoints are inclusive by default. You can add the word "exclusive"
938 before a value to make the comparison exclusive instead. Using a '*' indicates
939 no limit at that end of the range.
940  
941 =head2 one_of
942  
943 must => one_of(qw( a b c )),
944  
945 Returns a predicate that requires the value to exactly match one of the
946 enumerated values.
947  
948 =head2 split_by
949  
950 into => split_by(' ')
951 into => split_by(qr/,\s*/)
952 into => split_by(' ', 2)
953 into => split_by(qr/,\s*/, 10)
954  
955 Returns an into filter that splits the string into an array. The arguments are
956 similar to those accepted by Perl's built-in C<split>.
957  
958 =head2 trim
959  
960 into => trim
961 into => trim('left')
962 into => trim('right')
963  
964 Returns an into filter that trims whitespace from the input value. You can
965 provide an argument to trim only the left whitespace or the right whitespace.
966  
967 =head1 VALIDATION SPECIFICATIONS
968  
969 The validation specification is an array reference. Each key names a field to
970 validate. The value is an array of processing declarations. Each processing
971 declaration is a key-value pair. The inputs will be processed in the order they
972 appear in the spec. The key names the type of processing. The value describes
973 arguments for the processing. The processing declarations will each be executed
974 in the order they appear. The same processor may be applied multiple times.
975  
976 =head2 Input Declarations
977  
978 Input declarations modify the initial value and must be given at the very top of
979 the list of declarations for a field before all others.
980  
981 =head3 from
982  
983 from => 'input_parameter_name'
984  
985 Without this declaration, the validator pulls input from the parameter with the
986 same name as the key named in the validation spec. This input declaration
987 changes the key used for input.
988  
989 =head3 as
990  
991 multiple => 1
992  
993 The multiple input declaration tells the validator whether to interpret the
994 input parameter as a multiple input or not. Without this declaration or with it
995 set to 0, the validator will interpret multiple inputs as a single value,
996 ignoring all but the last. With this declaration, it treat the input as multiple
997 items, even if there are 0 or 1.
998  
999 =head3 trim
1000  
1001 trim => 0
1002  
1003 The default behavior of L</validate_form> is to trim whitespace from the beginning
1004 and end of a value before processing. You can use the C<trim> declaration to
1005 disable that.
1006  
1007 =head2 Filtering Declarations
1008  
1009 Filtering declarations inserted into the validation spec will replace the input
1010 value with the newly filtered value at the point at which the declaration is
1011 encountered.
1012  
1013 =head3 into
1014  
1015 into => '+'
1016 into => '?'
1017 into => '?+'
1018 into => '?perl'
1019 into => '?yes!no',
1020 into => '[]'
1021 into => '{}'
1022 into => 'Package::Name'
1023 into => sub { ... }
1024 into => TypeObject
1025  
1026 This is a filter declaration that transforms the input using the named coercion.
1027  
1028 =over
1029  
1030 =item Numeric
1031  
1032 Numeric coercion is performed using the '+' argument. This will convert the
1033 value using Perl's built-in string-to-number conversion.
1034  
1035 =item Boolean
1036  
1037 Boolean coercion is performed using the '?' argument. This will convert the
1038 value to boolean. It does not use Perl's normal mechanism, though. Instead, it
1039 converts the string to boolean based on string length alone. If the string is
1040 empty, it is false. If it is not empty it is true.
1041  
1042 =item Boolean by Numeric
1043  
1044 Boolean by Numeric coercion is performed using the '?+' argument. This will
1045 first convert the string input to a number and then the number will be collapsed
1046 to a boolean value such that 0 is false and any other value is true.
1047  
1048 =item Boolean via Perl
1049  
1050 Boolean via Perl coercion is performed using the '?perl' argument. This will
1051 convert to boolean using Perl's usual boolean logic.
1052  
1053 =item Boolean via Enumeration
1054  
1055 Boolean via Enumeration coercion is performed using an argument that starts with
1056 a question mark, '?', and contains an exclamation mark, '!'. The value between
1057 the question mark and exclamation mark is the value that must be provided for a
1058 true value. The value provided between the exclamation mark and the end of
1059 string is the false value. Anything else will be treated as invalid and cause a
1060 validation error.
1061  
1062 =item Array
1063  
1064 Using a value of '[]' will make sure the value is treated as an array. This is a
1065 noop if the L</multiple> declaration is set or if a L</filter> returns an array.
1066 If the value is still a single, though, this will make sure the input value is
1067 placed inside an array references. This will also turn a hash value into an array.
1068  
1069 =item Hash
1070  
1071 Setting the declaration to '{}" will coerce the value to a hash. The even indexed
1072 values in the array will become keys and the odd indexed values in the array
1073 will become their respective values. If the value is not an array, it will turn
1074 a single value into a key/value pair with the key and the pair both being equal
1075 to the original value.
1076  
1077 =item Package
1078  
1079 A package coercion happens when the string given is a package name. This assumes
1080 that passing the input value to the C<new> constructor of the named package will
1081 do the right thing. If you need anything more complicated than that, you should
1082 use a subroutine coercion.
1083  
1084 =item Subroutine
1085  
1086 A subroutine coercion converts the value using the given subroutine. The current
1087 input value is passed as the single argument to the coercion (and also set as
1088 the localized copy of C<$_>). The return value of the subroutine becomes the new
1089 input value.
1090  
1091 =item Type::Tiny Coercion
1092  
1093 If an object is passed that provides a C<coerce> method. That method will be
1094 called on the current input value and the result will be used as the new input
1095 value.
1096  
1097 =back
1098  
1099 =head3 each_into
1100  
1101 each_into => '+'
1102 each_into => '?'
1103 each_into => '?+'
1104 each_into => '?perl'
1105 each_into => '?yes!no',
1106 each_into => '[]'
1107 each_into => '{}'
1108 each_into => 'Package::Name'
1109 each_into => sub { ... }
1110 each_into => TypeObject
1111  
1112 Performs the same coercion as L</into>, but also works with arrays and hashes.
1113 It will apply the filter to a single value or to all elements of an array or to
1114 all keys and values of a hash.
1115  
1116 =head3 key_into
1117  
1118 key_into => '+'
1119 key_into => '?'
1120 key_into => '?+'
1121 key_into => '?perl'
1122 key_into => '?yes!no',
1123 key_into => '[]'
1124 key_into => '{}'
1125 key_into => 'Package::Name'
1126 key_into => sub { ... }
1127 key_into => TypeObject
1128  
1129 Performs the same coercion as L</into>, but also works with arrays and hashes.
1130 It will apply the filter to a single value or to all even index elements of an
1131 array or to all keys of a hash.
1132  
1133 =head3 value_into
1134  
1135 value_into => '+'
1136 value_into => '?'
1137 value_into => '?+'
1138 value_into => '?perl'
1139 value_into => '?yes!no',
1140 value_into => '[]'
1141 value_into => '{}'
1142 value_into => 'Package::Name'
1143 value_into => sub { ... }
1144 value_into => TypeObject
1145  
1146 Performs the same coercion as L</into>, but also works with arrays and hashes.
1147 It will apply the filter to a single value or to all odd index elements of an
1148 array or to all values of a hash.
1149  
1150 =head2 Validation Declarations
1151  
1152 =head3 required
1153  
1154 =head3 optional
1155  
1156 required => 1
1157 required => 0
1158 optional => 1
1159 optional => 0
1160  
1161 It is strongly recommended that all fields add this declaratoi immediately after
1162 the input declarations, if any.
1163  
1164 When required is set (or optional is set to 0), an initial validation check is
1165 inserted that will fail if a value is not provided for this field. That value
1166 must contain at least one character (after trimming, if trimming is not
1167 disabled).
1168  
1169 When optional is set (or required is set to 0), an initial validaiton check is
1170 inserted that will shortcircuit the rest of the validation if no value is
1171 provided.
1172  
1173 =head3 must
1174  
1175 must => qr/.../
1176 must => sub { ... }
1177 must => TypeObject
1178  
1179 This declaration states that the input given must match the described predicate.
1180 The module supports three kinds of predicates:
1181  
1182 =over
1183  
1184 =item Regular Expression
1185  
1186 This will match the given regular expression against the input. It is
1187 recommended that the regular expression start with "^" or "\A" and end with "$"
1188 or "\z" to force a total string match.
1189  
1190 The error message for these validates is not very good, so you probably want to
1191 combine use of this kind of predicate with a following L</with_error>
1192 declaration.
1193  
1194 =item Subroutine
1195  
1196 ($valid, $message) = $code->($value, \%fields);
1197  
1198 The subroutine will be passed two values. The first is the input to test
1199 (which will also be set in the localalized copy of C<$_>). This second value
1200 passed is rest of the input as processing currently stands.
1201  
1202 The return value must be a two elements list.
1203  
1204 =over
1205  
1206 =item 1.
1207  
1208 The first value returned is a boolean indicating whether the validation has
1209 passed. A true value (like 1) means validation passes and there's no error. A
1210 false value (like 0) means validation does not pass and an error has occured.
1211  
1212 There is a third option, which is to return C<undef>. This indicates that
1213 validaton should stop here. This is neither a success nor a failure. The value
1214 processed so far will be ignored, but no error message is returned either. Any
1215 further declarations for the field will be ignored as well.
1216  
1217 Returning C<undef> allows custom code to shortcircuit validation in exactly the
1218 same was as setting C<optional>.
1219  
1220 =item 2.
1221  
1222 The second value is the error message to use. It is acceptable to return an
1223 error message even if the first value is a true or undefined value. In that
1224 case, the error message will be ignored.
1225  
1226 =back
1227  
1228 =item Type::Tiny Object
1229  
1230 The third option is to use a L<Type::Tiny>-style type object. The
1231 L</validate_form> routine merely checks to see if it is an object that provides
1232 a C<check> method or a C<validate_form> method. If it provides a C<check>
1233 method, that method will be called and the boolean value returned will be
1234 treated as the success or failure to validate. In this case, the error message
1235 will be pulled from a call to C<get_message>, if such a method is provided. In
1236 the C<validate_form> case, it will be called and a true value will be treated as
1237 the error message and a false value as validation success.
1238  
1239 It is my experience that the error messages provided by L<Type::Tiny> and
1240 similar type systems are not friendly for use with end-uers. As such, it is
1241 recommended that you provide a nicer error message with a following
1242 L</with_error> declaration.
1243  
1244 =back
1245  
1246 =head3 each_must
1247  
1248 each_must => qr/.../
1249 each_must => sub { ... }
1250 each_must => TypeObject
1251  
1252 This declaration establishes validation rules just like L</must>, but applies
1253 the test to every value. If the input is an array, that will apply to every
1254 value. If the input is a hash, it will apply to every key and every value of the
1255 hash. If it is a single scalar, it will apply to that single value.
1256  
1257 =head3 key_must
1258  
1259 key_must => qr/.../
1260 key_must => sub { ... }
1261 key_must => TypeObject
1262  
1263 This is very similar to C<each_must>, but only applies to keys. It will apply to
1264 a single value, or to the even index values of an array, or to the keys of a
1265 hash.
1266  
1267 =head3 value_must
1268  
1269 value_must => qr/.../
1270 value_must => sub { ... }
1271 value_must => TypeObject
1272  
1273 This is very similar to C<each_must> and complement of C<key_must>. It will
1274 apply to a single value, or to the odd index values of an array, or to the
1275 values of a hash.
1276  
1277 =head3 with_error
1278  
1279 with_error => 'Error message.'
1280 with_error => sub { ... }
1281  
1282 This defines the error message to associate with the previous C<must>,
1283 C<each_must>, C<key_must>, C<value_must>, C<into>, C<required>, and C<optional>
1284 declaration. This will override any other associated message.
1285  
1286 If you would like to provide a different message based on the input, you may
1287 provide a subroutine.
1288  
1289 =head1 SPECIAL VARIABLES
1290  
1291 The validation specifications are defined in each packages where
1292 L</validation_spec> is called. This is done through a package variable named
1293 C<%FORM_VALIDATOR_TINY_SPECIFICATION>. If you really need to use that variable
1294 for something else or if defining global package variables offends you, you can
1295 use the return value form of C<validation_spec>, which will avoid creating this
1296 variable.
1297  
1298 If you stick to the regular interface, however, this variable will be
1299 established the first time C<validation_spec> is called. The spec names are the
1300 keys and the values have no documented definition. If you want to see what they
1301 are, you must the read the code, but there's no guarantee that the internal
1302 representation of this variable will stay the same in future releases.
1303  
1304 =head1 SEE ALSO
1305  
1306 L<Validate::Tiny> is very similar to this module in purpose and goals, but with
1307 a different API.
1308  
1309 =head1 AUTHOR
1310  
1311 Andrew Sterling Hanenkamp <hanenkamp@cpan.org>
1312  
1313 =head1 COPYRIGHT AND LICENSE
1314  
1315 This software is copyright (c) 2017 by Qubling Software LLC.
1316  
1317 This is free software; you can redistribute it and/or modify it under
1318 the same terms as the Perl 5 programming language system itself.
1319  
1320 =cut
1321  
1322 __END__
↑ Summary