Custom.pm

filter: Statementstmt 97.4% 304 / 312 Branchbran 94.2% 179 / 190 Conditioncond 76.1% 32 / 42 MC/DCmcdc 60.0% 15 / 25 Subroutinesub 96.5% 28 / 29 Podpod 66.6% 8 / 12 totaltotal 92.7% 566 / 610 CC 121 SCAR 36.1
CC
121
Cov
95%
validate
70.3
_parse_random_string_rule
15.1
_parse_constraint
14.0
CRAP 37.1
↑ Summary Custom/Constraint.pm »
1 package Validator::Custom;
2 5 ▶use Object::Simple -base;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 5 ▶use 5.008001;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 5 our $VERSION = '1.0201';
5  
6 5 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 5 ▶use Validator::Custom::Validation;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use Validator::Custom::FilterFunction;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use Validator::Custom::CheckFunction;
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 # Version 0 modules
12 5 ▶use Validator::Custom::Constraints;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 5 ▶use Validator::Custom::Constraint;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 5 ▶use Validator::Custom::Result;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 5 ▶use Validator::Custom::Rule;
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 18 ▶sub validation { Validator::Custom::Validation->new }
Subroutine validation: called CC=1 SCAR=0.0
Pod documented
18  
19 136 ▶sub new {
Subroutine new: called CC=1 SCAR=0.0
Pod documented
20 136 my $self = shift->SUPER::new(@_);
21
22 # Add checks
23 136 $self->add_check(
24 ascii_graphic => \&Validator::Custom::CheckFunction::ascii_graphic,
25 number => \&Validator::Custom::CheckFunction::number,
26 int => \&Validator::Custom::CheckFunction::int,
27 in => \&Validator::Custom::CheckFunction::in
28 );
29
30 # Add filters
31 136 $self->add_filter(
32 remove_blank => \&Validator::Custom::FilterFunction::remove_blank,
33 trim => \&Validator::Custom::FilterFunction::trim,
34 );
35
36 # Version 0 constraints
37 $self->register_constraint(
38 2 ▶ any => sub { 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
39 ascii => \&Validator::Custom::Constraint::ascii,
40 between => \&Validator::Custom::Constraint::between,
41 blank => \&Validator::Custom::Constraint::blank,
42 date_to_timepiece => \&Validator::Custom::Constraint::date_to_timepiece,
43 datetime_to_timepiece => \&Validator::Custom::Constraint::datetime_to_timepiece,
44 decimal => \&Validator::Custom::Constraint::decimal,
45 3 ▶ defined => sub { defined $_[0] },
Subroutine __ANON__: called CC=1 SCAR=0.0
46 136 duplication => \&Validator::Custom::Constraint::duplication,
47 equal_to => \&Validator::Custom::Constraint::equal_to,
48 greater_than => \&Validator::Custom::Constraint::greater_than,
49 http_url => \&Validator::Custom::Constraint::http_url,
50 int => \&Validator::Custom::Constraint::int,
51 in_array => \&Validator::Custom::Constraint::in_array,
52 length => \&Validator::Custom::Constraint::length,
53 less_than => \&Validator::Custom::Constraint::less_than,
54 merge => \&Validator::Custom::Constraint::merge,
55 not_defined => \&Validator::Custom::Constraint::not_defined,
56 not_space => \&Validator::Custom::Constraint::not_space,
57 not_blank => \&Validator::Custom::Constraint::not_blank,
58 uint => \&Validator::Custom::Constraint::uint,
59 regex => \&Validator::Custom::Constraint::regex,
60 selected_at_least => \&Validator::Custom::Constraint::selected_at_least,
61 shift => \&Validator::Custom::Constraint::shift_array,
62 space => \&Validator::Custom::Constraint::space,
63 string => \&Validator::Custom::Constraint::string,
64 to_array => \&Validator::Custom::Constraint::to_array,
65 to_array_remove_blank => \&Validator::Custom::Constraint::to_array_remove_blank,
66 trim => \&Validator::Custom::Constraint::trim,
67 trim_collapse => \&Validator::Custom::Constraint::trim_collapse,
68 trim_lead => \&Validator::Custom::Constraint::trim_lead,
69 trim_trail => \&Validator::Custom::Constraint::trim_trail,
70 trim_uni => \&Validator::Custom::Constraint::trim_uni,
71 trim_uni_collapse => \&Validator::Custom::Constraint::trim_uni_collapse,
72 trim_uni_lead => \&Validator::Custom::Constraint::trim_uni_lead,
73 trim_uni_trail => \&Validator::Custom::Constraint::trim_uni_trail
74 );
75
76 136 return $self;
77 }
78  
79 8 ▶sub check_each {
Subroutine check_each: called CC=8 SCAR=20.8
Pod documented
80 8 my ($self, $values, $name, $arg) = @_;
81
82 8 ▶ if (@_ < 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ < 3) 2 6 8
83 2 croak "values and the name of a checking function must be passed";
84 }
85
86 6 ▶ my $checks = $self->{checks} || {};
Condition50%1/2
$self->{'checks'} || {}
l!l
60
MC/DC0%0/1
$self->{'checks'} || {}
$self->{'checks'}
Truth table50%1/2
A
A= $self->{'checks'}
Aresult
11
00
87
88 croak "Can't call \"$name\" checking function"
89 6 ▶ unless $checks->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $checks->{$name} 1 5 6
90
91 5 ▶ croak "values must be array reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $values eq "ARRAY" 1 4 5
92 unless ref $values eq 'ARRAY';
93
94 4 my $is_invalid;
95 4 for my $value (@$values) {
96 7 my $is_valid = $checks->{$name}->($self, $value, $arg);
97 7 ▶ unless ($is_valid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_valid) 2 5 7
98 2 $is_invalid = 1;
99 2 last;
100 }
101 }
102
103 4 ▶ return $is_invalid ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$is_invalid ? : 2 2 4
104 }
105  
106 6 ▶sub filter_each {
Subroutine filter_each: called CC=6 SCAR=17.9
Pod documented
107 6 my ($self, $values, $name, $arg) = @_;
108
109 6 ▶ if (@_ < 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ < 3) 2 4 6
110 2 croak "values and the name of a filtering function must be passed";
111 }
112
113 4 ▶ my $filters = $self->{filters} || {};
Condition50%1/2
$self->{'filters'} || {}
l!l
40
MC/DC0%0/1
$self->{'filters'} || {}
$self->{'filters'}
Truth table50%1/2
A
A= $self->{'filters'}
Aresult
11
00
114
115 croak "Can't call \"$name\" filtering function"
116 4 ▶ unless $filters->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $filters->{$name} 1 3 4
117
118 3 ▶ croak "values must be array reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $values eq "ARRAY" 1 2 3
119 unless ref $values eq 'ARRAY';
120
121 2 my $new_values = [];
122 2 for my $value (@$values) {
123 4 my $new_value = $filters->{$name}->($self, $value, $arg);
124 4 push @$new_values, $new_value;
125 }
126
127 2 return $new_values;
128 }
129  
130 44 ▶sub check {
Subroutine check: called CC=4 SCAR=13.9
Pod documented
131 44 my ($self, $value, $name, $arg) = @_;
132  
133 44 ▶ if (@_ < 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ < 3) 2 42 44
134 2 croak "value and the name of a checking function must be passed";
135 }
136
137 42 ▶ my $checks = $self->{checks} || {};
Condition50%1/2
$self->{'checks'} || {}
l!l
420
MC/DC0%0/1
$self->{'checks'} || {}
$self->{'checks'}
Truth table50%1/2
A
A= $self->{'checks'}
Aresult
11
00
138
139 croak "Can't call \"$name\" checking function"
140 42 ▶ unless $checks->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $checks->{$name} 1 41 42
141
142 41 return $checks->{$name}->($self, $value, $arg);
143 }
144  
145 10 ▶sub filter {
Subroutine filter: called CC=4 SCAR=13.9
Pod documented
146 10 my ($self, $value, $name, $arg) = @_;
147
148 10 ▶ if (@_ < 3) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ < 3) 2 8 10
149 2 croak "value and the name of a filtering function must be passed";
150 }
151
152 8 ▶ my $filters = $self->{filters} || {};
Condition50%1/2
$self->{'filters'} || {}
l!l
80
MC/DC0%0/1
$self->{'filters'} || {}
$self->{'filters'}
Truth table50%1/2
A
A= $self->{'filters'}
Aresult
11
00
153
154 croak "Can't call \"$name\" filtering function"
155 8 ▶ unless $filters->{$name};
Branch: 1 branch
BranchTrueFalseTotal
unless $filters->{$name} 1 7 8
156
157 7 return $filters->{$name}->($self, $value, $arg);
158 }
159  
160 138 ▶sub add_check {
Subroutine add_check: called CC=3 SCAR=11.0
Pod documented
161 138 my $self = shift;
162
163 # Merge
164 138 ▶ my $checks = ref $_[0] eq 'HASH' ? $_[0] : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 138 138
165 138 ▶ $self->{checks} = ({%{$self->{checks} || {}}, %$checks});
Condition100%2/2
$self->{'checks'} || {}
l!l
2136
MC/DC100%1/1
$self->{'checks'} || {}
$self->{'checks'}
Truth table100%2/2
A
A= $self->{'checks'}
Aresult
11
00
166
167 138 return $self;
168 }
169  
170 138 ▶sub add_filter {
Subroutine add_filter: called CC=3 SCAR=11.0
Pod documented
171 138 my $self = shift;
172
173 # Merge
174 138 ▶ my $filters = ref $_[0] eq 'HASH' ? $_[0] : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 0 138 138
175 138 ▶ $self->{filters} = ({%{$self->{filters} || {}}, %$filters});
Condition100%2/2
$self->{'filters'} || {}
l!l
2136
MC/DC100%1/1
$self->{'filters'} || {}
$self->{'filters'}
Truth table100%2/2
A
A= $self->{'filters'}
Aresult
11
00
176
177 138 return $self;
178 }
179  
180 # Version 0 method
181 5 our %VALID_OPTIONS = map {$_ => 1} qw/message default copy require optional/;
182 452 ▶sub _parse_constraint {
Subroutine _parse_constraint: called CC=14 SCAR=26.4
183 452 my ($self, $c) = @_;
184  
185 # Constraint information
186 452 my $cinfo = {};
187  
188 # Arrange constraint information
189 452 my $constraint = $c->{constraint};
190 452 $cinfo->{message} = $c->{message};
191 452 $cinfo->{original_constraint} = $c->{constraint};
192
193 # Code reference
194 452 ▶ if (ref $constraint eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $constraint eq 'CODE') { } 19 433 452
195 19 $cinfo->{funcs} = [$constraint];
196 }
197 # Simple constraint name
198 else {
199 433 my $constraints;
200 433 ▶ if (ref $constraint eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $constraint eq 'ARRAY') { } 6 427 433
201 6 $constraints = $constraint;
202 }
203 else {
204 427 ▶ if ($constraint =~ /\|\|/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($constraint =~ /\|\|/) { } 13 414 427
205 13 $constraints = [split(/\|\|/, $constraint)];
206 }
207 else {
208 414 $constraints = [$constraint];
209 }
210 }
211
212 # Constraint functions
213 433 my @cfuncs;
214 my @cargs;
215 433 for my $cname (@$constraints) {
216 # Arrange constraint
217 457 ▶ if (ref $cname eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $cname eq "HASH") 108 349 457
218 108 my $first_key = (keys %$cname)[0];
219 108 push @cargs, $cname->{$first_key};
220 108 $cname = $first_key;
221 }
222  
223 # Target is array elements
224 457 ▶ $cinfo->{each} = 1 if $cname =~ s/^@//;
Branch: 1 branch
BranchTrueFalseTotal
if $cname =~ s/^@// 18 439 457
225 457 ▶ croak qq{"\@" must be one at the top of constrinat name}
Branch: 1 branch
BranchTrueFalseTotal
if index($cname, "\@") != -1 0 457 457
226 if index($cname, '@') > -1;
227
228
229 # Trim space
230 457 $cname =~ s/^\s+//;
231 457 $cname =~ s/\s+$//;
232
233 # Negative
234 457 ▶ my $negative = $cname =~ s/^!// ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$cname =~ s/^!// ? : 9 448 457
235 457 ▶ croak qq{"!" must be one at the top of constraint name}
Branch: 1 branch
BranchTrueFalseTotal
if index($cname, "!") != -1 0 457 457
236 if index($cname, '!') > -1;
237
238 # Trim space
239 457 $cname =~ s/^\s+//;
240 457 $cname =~ s/\s+$//;
241
242 # Constraint function
243 457 ▶ croak "Constraint name '$cname' must be [A-Za-z0-9_]"
Branch: 1 branch
BranchTrueFalseTotal
if $cname =~ /\W/ 1 456 457
244 if $cname =~ /\W/;
245 456 ▶ my $cfunc = $self->constraints->{$cname} || '';
Condition100%2/2
$self->constraints->{$cname} || ''
l!l
4551
MC/DC100%1/1
$self->constraints->{$cname} || ''
$self->constraints->{$cname}
Truth table100%2/2
A
A= $self->constraints->{$cname}
Aresult
11
00
246 456 ▶ croak qq{"$cname" is not registered}
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cfunc eq "CODE" 1 455 456
247 unless ref $cfunc eq 'CODE';
248
249 # Negativate
250 9 ▶ my $f = $negative ? sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
251 9 my $ret = $cfunc->(@_);
252 9 ▶ if (ref $ret eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $ret eq 'ARRAY') { } 2 7 9
253 2 $ret->[0] = ! $ret->[0];
254 2 return $ret;
255 }
256 7 else { return !$ret }
257 455 ▶ } : $cfunc;
Branch: 1 branch
BranchTrueFalseTotal
$negative ? : 9 446 455
258
259 # Add
260 455 push @cfuncs, $f;
261 }
262 431 $cinfo->{funcs} = \@cfuncs;
263 431 $cinfo->{args} = \@cargs;
264 }
265
266 450 return $cinfo;
267 }
268  
269 103 ▶has shared_rule => sub { [] };
Subroutine __ANON__: called CC=1 SCAR=0.0
270 139 ▶__PACKAGE__->attr('constraints' => sub { {} });
Subroutine __ANON__: called CC=1 SCAR=0.0
271  
272 # Version 0 method
273 173 ▶sub create_rule { Validator::Custom::Rule->new(validator => shift) }
Subroutine create_rule: called CC=1 SCAR=0.0
Pod undocumented
274  
275 # Version 0 method
276 165 ▶sub register_constraint {
Subroutine register_constraint: called CC=2 SCAR=6.9
Pod undocumented
277 165 my $self = shift;
278
279 # Merge
280 165 ▶ my $constraints = ref $_[0] eq 'HASH' ? $_[0] : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 6 159 165
281 165 $self->constraints({%{$self->constraints}, %$constraints});
282
283 165 return $self;
284 }
285  
286 # Version 0 method
287 1 ▶sub _parse_random_string_rule {
Subroutine _parse_random_string_rule: called CC=15 SCAR=27.1
288 1 my $self = shift;
289
290 # Rule
291 1 ▶ my $rule = ref $_[0] eq 'HASH' ? $_[0] : {@_};
Branch: 1 branch
BranchTrueFalseTotal
ref $_[0] eq 'HASH' ? : 1 0 1
292
293 # Result
294 1 my $result = {};
295
296 # Parse string rule
297 1 for my $name (keys %$rule) {
298 # Pettern
299 5 my $pattern = $rule->{$name};
300 5 ▶ $pattern = '' unless $pattern;
Branch: 1 branch
BranchTrueFalseTotal
unless $pattern 1 4 5
301
302 # State
303 5 my $state = 'character';
304  
305 # Count
306 5 my $count = '';
307
308 # Chacacter sets
309 5 my $csets = [];
310 5 my $cset = [];
311
312 # Parse pattern
313 5 my $c;
314 5 ▶ while (defined ($c = substr($pattern, 0, 1, '')) && length $c) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined($c = substr($pattern, 0, 1, '')) and length $c) 42 5 47
Condition66%2/3
defined($c = substr($pattern, 0, 1, '')) and length $c
!ll&&!rl&&r
0542
MC/DC50%1/2
defined($c = substr($pattern, 0, 1, '')) and length $c
defined($c = substr($pattern, 0, 1, '')) length $c
Truth table66%2/3
A and B
A= defined($c = substr($pattern, 0, 1, ''))B= length $c
ABresult
0X0
100
111
315 # Character class
316 42 ▶ if ($state eq 'character_class') {
Branch: 2 branches
BranchTrueFalseTotal
if ($state eq 'character_class') { } 9 33 42
elsif ($state eq 'count') { } 13 20 33
317 9 ▶ if ($c eq ']') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq ']') { } 3 6 9
318 3 $state = 'character';
319 3 push @$csets, $cset;
320 3 $cset = [];
321 3 $state = 'character';
322 }
323 6 else { push @$cset, $c }
324 }
325
326 # Count
327 elsif ($state eq 'count') {
328 13 ▶ if ($c eq '}') {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq '}') { } 6 7 13
329 6 ▶ $count = 1 if $count < 1;
Branch: 1 branch
BranchTrueFalseTotal
if $count < 1 0 6 6
330 6 ▶ for (my $i = 0; $i < $count - 1; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < $count - 1) 14 6 20
331 14 ▶ push @$csets, [@{$csets->[-1] || ['']}];
Condition50%1/2
$csets->[-1] || ['']
l!l
140
MC/DC0%0/1
$csets->[-1] || ['']
$csets->[-1]
Truth table50%1/2
A
A= $csets->[-1]
Aresult
11
00
332 }
333 6 $count = '';
334 6 $state = 'character';
335 }
336 7 else { $count .= $c }
337 }
338
339 # Character
340 else {
341 20 ▶ if ($c eq '[') { $state = 'character_class' }
Branch: 2 branches
BranchTrueFalseTotal
if ($c eq '[') { } 3 17 20
elsif ($c eq '{') { } 6 11 17
342 6 elsif ($c eq '{') { $state = 'count' }
343 11 else { push @$csets, [$c] }
344 }
345 }
346
347 # Add Charcter sets
348 5 $result->{$name} = $csets;
349 }
350
351 1 return $result;
352 }
353  
354 # Version 0 method
355 177 ▶sub validate {
Subroutine validate: called CC=70 SCAR=42.5
Pod undocumented
356 177 my ($self, $input, $rule) = @_;
357
358 # Class
359 177 my $class = ref $self;
360
361 # Validation rule
362 177 ▶ $rule ||= $self->rule;
Condition100%3/3
$rule ||= $self->rule
l!l&&r!l&&!r
16881
MC/DC100%2/2
$rule ||= $self->rule
$rule $self->rule
Truth table100%3/3
A ||= B
A= $ruleB= $self->rule
ABresult
1X1
011
000
363
364 # Data filter
365 177 my $filter = $self->data_filter;
366 177 ▶ $input = $filter->($input) if $filter;
Branch: 1 branch
BranchTrueFalseTotal
if $filter 1 176 177
367
368 # Check data
369 177 ▶ croak "First argument must be hash ref"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $input eq "HASH" 1 176 177
370 unless ref $input eq 'HASH';
371
372 # Check rule
373 176 ▶ unless (ref $rule eq 'Validator::Custom::Rule') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $rule eq "Validator::Custom::Rule") 159 17 176
374 159 ▶ croak "Invalid rule structure" unless ref $rule eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rule eq "ARRAY" 1 158 159
375 }
376
377 # Result
378 175 my $result = Validator::Custom::Result->new;
379 175 $result->{_error_infos} = {};
380
381 # Save raw data
382 175 $result->raw_data($input);
383
384 # Error is stock?
385 175 my $error_stock = $self->error_stock;
386
387 # Valid keys
388 175 my $valid_keys = {};
389
390 # Error position
391 175 my $pos = 0;
392
393 # Found missing parameters
394 175 my $found_missing_params = {};
395
396 # Shared rule
397 175 my $shared_rule = $self->shared_rule;
398
399 175 ▶ if (ref $rule eq 'Validator::Custom::Rule') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $rule eq 'Validator::Custom::Rule') { } 17 158 175
400 17 $self->rule_obj($rule);
401 }
402 else {
403 158 my $rule_obj = $self->create_rule;
404 158 $rule_obj->parse($rule, $shared_rule);
405 156 $self->rule_obj($rule_obj);
406 }
407 173 my $rule_obj = $self->rule_obj;
408  
409 173 ▶ if ($rule_obj->{version} && $rule_obj->{version} == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rule_obj->{"version"} and $rule_obj->{"version"} == 1) 0 173 173
Condition33%1/3
$rule_obj->{"version"} and $rule_obj->{"version"} == 1
!ll&&!rl&&r
17300
MC/DC0%0/2
$rule_obj->{"version"} and $rule_obj->{"version"} == 1
$rule_obj->{"version"} $rule_obj->{"version"} == 1
Truth table33%1/3
A and B
A= $rule_obj->{"version"}B= $rule_obj->{"version"} == 1
ABresult
0X0
100
111
410 0 croak "Can't call validate method(Validator::Custom). Use \$rule->validate(\$input) instead";
411 }
412
413 # Process each key
414 OUTER_LOOP:
415 173 ▶ for (my $i = 0; $i < @{$rule_obj->rule}; $i++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @{$rule_obj->rule;}) 407 157 564
416
417 407 my $r = $rule_obj->rule->[$i];
418
419 # Increment position
420 407 $pos++;
421
422 # Key, options, and constraints
423 407 my $key = $r->{key};
424 407 my $opts = $r->{option};
425 407 ▶ my $cinfos = $r->{constraints} || [];
Condition100%2/2
$r->{'constraints'} || []
l!l
4034
MC/DC100%1/1
$r->{'constraints'} || []
$r->{'constraints'}
Truth table100%2/2
A
A= $r->{'constraints'}
Aresult
11
00
426
427 # Check constraints
428 407 ▶ croak "Invalid rule structure"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cinfos eq "ARRAY" 2 405 407
429 unless ref $cinfos eq 'ARRAY';
430  
431 # Arrange key
432 405 my $result_key = $key;
433 405 ▶ if (ref $key eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $key eq 'HASH') { } 49 356 405
elsif (defined $r->{'name'}) { } 0 356 356
434 49 my $first_key = (keys %$key)[0];
435 49 $result_key = $first_key;
436 49 $key = $key->{$first_key};
437 }
438 elsif (defined $r->{name}) {
439 0 $result_key = $r->{name};
440 }
441
442 # Real keys
443 405 my $keys;
444
445 405 ▶ if (ref $key eq 'ARRAY') { $keys = $key }
Branch: 2 branches
BranchTrueFalseTotal
if (ref $key eq 'ARRAY') { } 49 356 405
elsif (ref $key eq 'Regexp') { } 2 354 356
446 elsif (ref $key eq 'Regexp') {
447 2 $keys = [];
448 2 for my $k (keys %$input) {
449 5 ▶ push @$keys, $k if $k =~ /$key/;
Branch: 1 branch
BranchTrueFalseTotal
if $k =~ /$key/ 4 1 5
450 }
451 }
452 354 else { $keys = [$key] }
453
454 # Check option
455 405 ▶ if (exists $opts->{optional}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts->{"optional"}) 1 404 405
456 1 ▶ if ($opts->{optional}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"optional"}) 1 0 1
457 1 $opts->{require} = 0;
458 }
459 1 delete $opts->{optional};
460 }
461 405 for my $oname (keys %$opts) {
462 croak qq{Option "$oname" of "$result_key" is invalid name}
463 25 ▶ unless $VALID_OPTIONS{$oname};
Branch: 1 branch
BranchTrueFalseTotal
unless $Validator::Custom::VALID_OPTIONS{$oname} 0 25 25
464 }
465
466 # Default
467 405 ▶ if (exists $opts->{default}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts->{"default"}) 8 397 405
468 8 $r->{default} = $opts->{default};
469 }
470
471 # Is data copy?
472 405 my $copy = 1;
473 405 ▶ $copy = $opts->{copy} if exists $opts->{copy};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"copy"} 4 401 405
474
475 # Check missing parameters
476 405 ▶ my $require = exists $opts->{require} ? $opts->{require} : 1;
Branch: 1 branch
BranchTrueFalseTotal
exists $opts->{'require'} ? : 5 400 405
477 405 my $found_missing_param;
478 405 my $missing_params = $result->missing_params;
479 405 for my $key (@$keys) {
480 551 ▶ unless (exists $input->{$key}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $input->{$key}) 16 535 551
481 16 ▶ if ($require && !exists $r->{default}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($require and not exists $r->{"default"}) 10 6 16
Condition100%3/3
$require and not exists $r->{"default"}
!ll&&!rl&&r
3310
MC/DC100%2/2
$require and not exists $r->{"default"}
$require not exists $r->{"default"}
Truth table100%3/3
A and not(B)
A= $requireB= not exists $r->{"default"}
ABresult
0X0
100
111
482 push @$missing_params, $key
483 10 ▶ unless $found_missing_params->{$key};
Branch: 1 branch
BranchTrueFalseTotal
unless $found_missing_params->{$key} 9 1 10
484 10 $found_missing_params->{$key}++;
485 }
486 16 $found_missing_param = 1;
487 }
488 }
489 405 ▶ if ($found_missing_param) {
Branch: 1 branch
BranchTrueFalseTotal
if ($found_missing_param) 15 390 405
490 $result->data->{$result_key} = ref $r->{default} eq 'CODE'
491 ? $r->{default}->($self) : $r->{default}
492 15 ▶ if exists $r->{default} && $copy;
Branch: 2 branches
BranchTrueFalseTotal
if exists $r->{"default"} and $copy 2 13 15
ref $r->{'default'} eq 'CODE' ? : 1 1 2
Condition100%3/3
exists $r->{"default"} and $copy
!ll&&!rl&&r
1212
MC/DC100%2/2
exists $r->{"default"} and $copy
exists $r->{"default"} $copy
Truth table100%3/3
A and B
A= exists $r->{"default"}B= $copy
ABresult
0X0
100
111
493 15 ▶ next if $r->{default} || !$require;
Branch: 1 branch
BranchTrueFalseTotal
if $r->{"default"} or not $require 6 9 15
Condition100%3/3
$r->{"default"} or not $require
l!l&&r!l&&!r
339
MC/DC100%2/2
$r->{"default"} or not $require
$r->{"default"} not $require
Truth table100%3/3
A or not(B)
A= $r->{"default"}B= not $require
ABresult
1X1
011
000
494 }
495
496 # Already valid
497 399 ▶ next if $valid_keys->{$result_key};
Branch: 1 branch
BranchTrueFalseTotal
if $valid_keys->{$result_key} 3 396 399
498
499 # Validation
500 my $value = @$keys > 1
501 196 ? [map { $input->{$_} } @$keys]
502 396 ▶ : $input->{$keys->[0]};
Branch: 1 branch
BranchTrueFalseTotal
@$keys > 1 ? : 50 346 396
503
504 396 for my $cinfo (@$cinfos) {
505
506 # Constraint information
507 427 my $args = $cinfo->{args};
508 427 my $message = $cinfo->{message};
509
510 # Constraint function
511 427 my $cfuncs = $cinfo->{funcs};
512
513 # Is valid?
514 427 my $is_valid;
515
516 # Data is array
517 427 ▶ if($cinfo->{each}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cinfo->{'each'}) { } 21 406 427
518
519 # To array
520 21 ▶ $value = [$value] unless ref $value eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $value eq "ARRAY" 4 17 21
521
522 # Validation loop
523 21 ▶ for (my $k = 0; $k < @$value; $k++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < @$value) 37 14 51
524 37 my $input = $value->[$k];
525
526 # Validation
527 37 ▶ for (my $j = 0; $j < @$cfuncs; $j++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($j < @$cfuncs) 43 7 50
528 43 my $cfunc = $cfuncs->[$j];
529 43 my $arg = $args->[$j];
530
531 # Validate
532 43 my $cresult;
533 {
534 43 local $_ = Validator::Custom::Constraints->new(
535 constraints => $self->constraints
536 );
537 43 $cresult= $cfunc->($input, $arg, $self);
538 }
539
540 # Constrint result
541 43 my $v;
542 43 ▶ if (ref $cresult eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $cresult eq 'ARRAY') { } 18 25 43
elsif (ref $cresult eq 'HASH') { } 4 21 25
543 18 ($is_valid, $v) = @$cresult;
544 18 $value->[$k] = $v;
545 }
546 elsif (ref $cresult eq 'HASH') {
547 4 $is_valid = $cresult->{result};
548 4 ▶ $message = $cresult->{message} unless $is_valid;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_valid 1 3 4
549 4 ▶ $value->[$k] = $cresult->{output} if exists $cresult->{output};
Branch: 1 branch
BranchTrueFalseTotal
if exists $cresult->{"output"} 2 2 4
550 }
551 21 else { $is_valid = $cresult }
552
553 43 ▶ last if $is_valid;
Branch: 1 branch
BranchTrueFalseTotal
if $is_valid 30 13 43
554 }
555
556 # Validation error
557 37 ▶ last unless $is_valid;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_valid 7 30 37
558 }
559 }
560
561 # Data is scalar
562 else {
563 # Validation
564 406 ▶ for (my $k = 0; $k < @$cfuncs; $k++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < @$cfuncs) 418 190 608
565 418 my $cfunc = $cfuncs->[$k];
566 418 my $arg = $args->[$k];
567
568 418 my $cresult;
569 {
570 418 local $_ = Validator::Custom::Constraints->new(
571 constraints => $self->constraints
572 );
573 418 $cresult = $cfunc->($value, $arg, $self);
574 }
575
576 407 ▶ if (ref $cresult eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $cresult eq 'ARRAY') { } 95 312 407
elsif (ref $cresult eq 'HASH') { } 2 310 312
577 95 my $v;
578 95 ($is_valid, $v) = @$cresult;
579 95 ▶ $value = $v if $is_valid;
Branch: 1 branch
BranchTrueFalseTotal
if $is_valid 56 39 95
580 }
581 elsif (ref $cresult eq 'HASH') {
582 2 $is_valid = $cresult->{result};
583 2 ▶ $message = $cresult->{message} unless $is_valid;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_valid 1 1 2
584 2 ▶ $value = $cresult->{output} if exists $cresult->{output} && $is_valid;
Branch: 1 branch
BranchTrueFalseTotal
if exists $cresult->{"output"} and $is_valid 1 1 2
Condition66%2/3
exists $cresult->{"output"} and $is_valid
!ll&&!rl&&r
101
MC/DC50%1/2
exists $cresult->{"output"} and $is_valid
exists $cresult->{"output"} $is_valid
Truth table66%2/3
A and B
A= exists $cresult->{"output"}B= $is_valid
ABresult
0X0
100
111
585 }
586 310 else { $is_valid = $cresult }
587
588 407 ▶ last if $is_valid;
Branch: 1 branch
BranchTrueFalseTotal
if $is_valid 205 202 407
589 }
590 }
591
592 # Add error if it is invalid
593 416 ▶ unless ($is_valid) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_valid) 197 219 416
594 197 ▶ if (exists $r->{default}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $r->{'default'}) { } 6 191 197
595 # Set default value
596 $result->data->{$result_key} = ref $r->{default} eq 'CODE'
597 ? $r->{default}->($self)
598 : $r->{default}
599 6 ▶ if exists $r->{default} && $copy;
Branch: 2 branches
BranchTrueFalseTotal
if exists $r->{"default"} and $copy 5 1 6
ref $r->{'default'} eq 'CODE' ? : 1 4 5
Condition66%2/3
exists $r->{"default"} and $copy
!ll&&!rl&&r
015
MC/DC50%1/2
exists $r->{"default"} and $copy
exists $r->{"default"} $copy
Truth table66%2/3
A and B
A= exists $r->{"default"}B= $copy
ABresult
0X0
100
111
600 6 $valid_keys->{$result_key} = 1
601 }
602 else {
603 # Resist error info
604 191 ▶ $message = $opts->{message} unless defined $message;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $message 147 44 191
605 $result->{_error_infos}->{$result_key} = {
606 message => $message,
607 position => $pos,
608 reason => $cinfo->{original_constraint},
609 original_key => $key
610 191 ▶ } unless exists $result->{_error_infos}->{$result_key};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $result->{"_error_infos"}{$result_key} 186 5 191
611
612 # No Error stock
613 191 ▶ unless ($error_stock) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($error_stock) 5 186 191
614 # Check rest constraint
615 5 my $found;
616 5 ▶ for (my $k = $i + 1; $k < @{$rule_obj->rule}; $k++) {
Branch: 1 branch
BranchTrueFalseTotal
if ($k < @{$rule_obj->rule;}) 8 5 13
617 8 my $r_next = $rule_obj->rule->[$k];
618 8 my $key_next = $r_next->{key};
619 8 ▶ $key_next = (keys %$key)[0] if ref $key eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $key eq "HASH" 0 8 8
620 8 ▶ $found = 1 if $key_next eq $result_key;
Branch: 1 branch
BranchTrueFalseTotal
if $key_next eq $result_key 3 5 8
621 }
622 5 ▶ last OUTER_LOOP unless $found;
Branch: 1 branch
BranchTrueFalseTotal
unless $found 3 2 5
623 }
624 }
625 194 next OUTER_LOOP;
626 }
627 }
628
629 # Result data
630 188 ▶ $result->data->{$result_key} = $value if $copy;
Branch: 1 branch
BranchTrueFalseTotal
if $copy 186 2 188
631
632 # Key is valid
633 188 $valid_keys->{$result_key} = 1;
634
635 # Remove invalid key
636 188 delete $result->{_error_infos}->{$key};
637 }
638
639 160 return $result;
640 }
641  
642 # Version 0 attributes
643 5 has 'data_filter';
644 5 has 'rule';
645 5 has 'rule_obj';
646 5 has error_stock => 1;
647  
648 # Version 0 method
649 0 ▶sub js_fill_form_button {
Subroutine js_fill_form_button: not called CC=1 SCAR=6.9
Pod undocumented
650 0 my ($self, $rule) = @_;
651
652 0 my $r = $self->_parse_random_string_rule($rule);
653
654 0 require JSON;
655 0 my $r_json = JSON->new->encode($r);
656
657 0 my $javascript = << "EOS";
658 (function () {
659  
660 var rule = $r_json;
661  
662 var create_random_value = function (rule, name) {
663 var patterns = rule[name];
664 if (patterns === undefined) {
665 return "";
666 }
667
668 var value = "";
669 for (var i = 0; i < patterns.length; i++) {
670 var pattern = patterns[i];
671 var num = Math.floor(Math.random() * pattern.length);
672 value = value + pattern[num];
673 }
674
675 return value;
676 };
677
678 var addEvent = (function(){
679 if(document.addEventListener) {
680 return function(node,type,handler){
681 node.addEventListener(type,handler,false);
682 };
683 } else if (document.attachEvent) {
684 return function(node,type,handler){
685 node.attachEvent('on' + type, function(evt){
686 handler.call(node, evt);
687 });
688 };
689 }
690 })();
691
692 var button = document.createElement("input");
693 button.setAttribute("type","button");
694 button.value = "Fill Form";
695 document.body.insertBefore(button, document.body.firstChild)
696  
697 addEvent(
698 button,
699 "click",
700 function () {
701
702 var input_elems = document.getElementsByTagName('input');
703 var radio_names = {};
704 var checkbox_names = {};
705 for (var i = 0; i < input_elems.length; i++) {
706 var e = input_elems[i];
707  
708 var name = e.getAttribute("name");
709 var type = e.getAttribute("type");
710 if (type === "text" || type === "hidden" || type === "password") {
711 var value = create_random_value(rule, name);
712 e.value = value;
713 }
714 else if (type === "checkbox") {
715 e.checked = Math.floor(Math.random() * 2) ? true : false;
716 }
717 else if (type === "radio") {
718 radio_names[name] = 1;
719 }
720 }
721
722 for (name in radio_names) {
723 var elems = document.getElementsByName(name);
724 var num = Math.floor(Math.random() * elems.length);
725 elems[num].checked = true;
726 }
727
728 var textarea_elems = document.getElementsByTagName("textarea");
729 for (var i = 0; i < textarea_elems.length; i++) {
730 var e = textarea_elems[i];
731
732 var name = e.getAttribute("name");
733 var value = create_random_value(rule, name);
734
735 var text = document.createTextNode(value);
736
737 if (e.firstChild) {
738 e.removeChild(e.firstChild);
739 }
740
741 e.appendChild(text);
742 }
743
744 var select_elems = document.getElementsByTagName("select");
745 for (var i = 0; i < select_elems.length; i++) {
746 var e = select_elems[i];
747 var options = e.options;
748 if (e.multiple) {
749 for (var k = 0; k < options.length; k++) {
750 options[k].selected = Math.floor(Math.random() * 2) ? true : false;
751 }
752 }
753 else {
754 var num = Math.floor(Math.random() * options.length);
755 e.selectedIndex = num;
756 }
757 }
758 }
759 );
760 })();
761 EOS
762  
763 0 return $javascript;
764 }
765  
766 5 1;
767  
768 =encoding UTF-8
769  
770 =head1 NAME
771  
772 Validator::Custom - HTML form validation. Simple and good flexibility
773  
774 =head1 DESCRIPTION
775  
776 L<Validator::Custom> is a validator for HTML form.
777  
778 =over 4
779  
780 =item *
781  
782 1. B<Checking functions:> C<ascii_graphic>, C<int>, C<number>, C<in>. You can also add your checking function.
783  
784 =item *
785  
786 2. B<Filtering functions:> C<trim>, C<remove_blank>. You can also add your filtering function.
787  
788 =item *
789  
790 3. B<Validation object:> Save each validation result and check if all data is valid.
791  
792 =back
793  
794 =head1 SYNOPSIS
795  
796 use Validator::Custom;
797 my $vc = Validator::Custom->new;
798
799 # Input data
800 my $id = 1;
801 my $name = 'Ken Suzuki';
802 my $price = ' 19.23 ';
803 my $favorite = ['001', '002'];
804
805 # Create validation object
806 my $validation = $vc->validation;
807
808 # Check if id is integer
809 if (!$vc->check($id, 'int')) {
810 # Add failed message
811 $validation->add_failed(id => 'id must be integer');
812 }
813
814 # Check if name has length
815 if (!(length $name)) {
816 $validation->add_failed(name => 'name must have length');
817 }
818 # Check if name's length is less than 30
819 elsif (!(length $name < 30)) {
820 $validation->add_failed(name => 'name is too long');
821 }
822
823 # Filter price to remove left-rigth space
824 $price = $vc->filter($price, 'trim');
825  
826 # Check price is number and the digits of the decimal part is two or less than two
827 if (!$vc->check($price, 'number', {decimal_part_max => 2})) {
828 # Set default value if validation fail
829 $price = 20.25;
830 }
831
832 # Filter each value of favorite using "trim" filtering function
833 $favorite = $vc->filter_each($favorite, 'trim');
834
835 # Check if favorite has at least one values
836 if (@$favorite == 0) {
837 $validation->add_failed(favorite => 'favorite must be selected more than one');
838 }
839 # Check if favorite is one of the specified values
840 elsif (!($vc->check_each($favorite, 'in', ['001', '002', '003']))) {
841 $validation->add_failed(favorite => 'favorite is invalid');
842 }
843
844 # Check if validation result is valid
845 if ($validation->is_valid) {
846 # ...
847 }
848 else {
849
850 # Check what parameter fail
851 unless ($validation->is_valid('name')) {
852 # ...
853 }
854
855 # Get all failed parameter names
856 my $failed = $validation->failed;
857  
858 # Get a failed parameter message
859 my $name_message = $validation->message('name');
860
861 # Get all failed parameter messages
862 my $messages = $validation->messages;
863
864 # Get all failed parameter names and the messages as hash reference
865 my $messages_h = $validation->messages_to_hash;
866 }
867
868 =head1 1. Basic usage
869  
870 =head2 1. Create a new Validator::Custom object
871  
872 At first, create L<Validator::Custom> object using C<new> method.
873  
874 use Validator::Custom;
875 my $vc = Validator::Custom->new;
876  
877 =head2 2. Prepare input data for validation
878  
879 Next, prepare input data.
880  
881 my $id = 1;
882 my $name = 'Ken Suzuki';
883 my $price = ' 19.23 ';
884 my $favorite = ['001', '002'];
885  
886 =head2 3. Create a new validation object
887  
888 Next, create a new validation object using C<validation> method.
889  
890 my $validation = $vc->validation;
891  
892 This is L<Validator::Custom::Validation> object
893 to store failed parameter names and the messages.
894  
895 =head2 4. Validate input data
896  
897 # Check if id is integer
898 if (!$vc->check($id, 'int')) {
899 # Add failed message
900 $validation->add_failed(id => 'id must be integer');
901 }
902  
903 You can use C<int> checking function to check the value is integer.
904 C<int> checking function is default one.
905 Any checking function is available through C<check> method.
906  
907 When the check doesn't succeed, you can add the failed parameter name and the message
908 using C<add_failed> method of L<Validator::Custom::Validation> class.
909
910 # Filter price to remove left-rigth space
911 $price = $vc->filter($price, 'trim');
912  
913 You can use C<trim> filtering function to trim left-rigth spaces.
914
915 # Filter each value of favorite using "trim" filtering function
916 $favorite = $vc->filter_each($favorite, 'trim');
917  
918 You can use C<filter_each> method to filter each value of favorite.
919
920 # Check if favorite has at least one values
921 if (@$favorite == 0) {
922 $validation->add_failed(favorite => 'favorite must be selected more than one');
923 }
924 # Check if favorite is one of the specified values
925 elsif (!($vc->check_each($favorite, 'in', ['001', '002', '003']))) {
926 $validation->add_failed(favorite => 'favorite is invalid');
927 }
928  
929 You can use C<check_each> method to check each value of favorite.
930  
931 If you see default checks and filter,
932 see L<Validator::Custom/"CHECKING FUNCTIONS"> and L<Validator::Custom/"FILTERING FUNCTIONS">.
933  
934 =head1 2. Manipulate validation object
935  
936 If you check all input data is valid, use C<is_valid> method.
937
938 # Check if validation result is valid
939 if ($validation->is_valid) {
940 # Success
941 }
942 else {
943 # Failed
944 }
945  
946 If you can check a input data is valid, use C<is_valid> method with parameter name.
947
948 # Check what parameter fail
949 unless ($validation->is_valid('name')) {
950 # ...
951 }
952  
953 You can get all failed parameter names using C<failed> method.
954  
955 # Get all failed parameter names
956 my $failed = $validation->failed;
957  
958 You can get a failed parameter message using C<message> method.
959  
960 # Get a failed parameter message
961 my $name_message = $validation->message('name');
962  
963 You can get all failed parameter messages using C<messages> method.
964  
965 # Get all failed parameter messages
966 my $messages = $validation->messages;
967  
968 You can get all failed names and the messages as hash reference using C<messages_to_hash> method.
969  
970 # Get all failed parameter names and the messages as hash reference
971 my $messages_h = $validation->messages_to_hash;
972  
973 See also L<Validator::Custom::Validation>.
974  
975 =head1 3. Advanced tequnique
976  
977 =head2 1. Add checking function
978  
979 You can add your own checking function using C<add_check> method if you need.
980  
981 $vc->add_check(
982 telephone => sub {
983 my ($vc, $value, $arg) = @_;
984
985 my $is_valid;
986 if ($value =~ /^[\d-]+$/) {
987 $is_valid = 1;
988 }
989 return $is_valid;
990 }
991 );
992  
993 Checking function receives three arguments,
994 First argument is L<Validator::Custom> object,
995 Second argument is the value for checking,
996 Third argument is the argument of checking function.
997  
998 Your Checking function must return true or false value.
999  
1000 =head2 2. Add filtering function
1001  
1002 You can add your filtering function by C<add_filter> method if you need.
1003  
1004 $vc->add_filter(
1005 to_upper_case => sub {
1006 my ($vc, $value, $arg) = @_;
1007
1008 my $new_$value = uc $value;
1009
1010 return $new_value;
1011 }
1012 );
1013  
1014 Filtering function receives three arguments,
1015 First argument is L<Validator::Custom> object,
1016 Second argument is the value for filtering.
1017 Third argument is the argument of filtering function.
1018  
1019 Your filtering function must return the result of filtering.
1020  
1021 =head1 Checking functions
1022  
1023 L<Validator::Custom> have the following default checking functions.
1024 You can call any checking function by C<check> method.
1025  
1026 =head2 int
1027  
1028 Check if the value is integer value.
1029  
1030 my $value = 19;
1031 my $is_valid = $vc->check($value, 'int');
1032  
1033 Example of valid values:
1034  
1035 "-10"
1036 "234"
1037  
1038 Example of invalid values:
1039  
1040 "10.11"
1041 "abc"
1042  
1043 If you also need to check the range of value, you can write the following way.
1044  
1045 my $is_valid = $vc->check($value, 'int') && $value > 0;
1046  
1047 =head2 number
1048  
1049 Check if the value is number.
1050 Number means integer or decimal.
1051
1052 my $is_valid = $vc->check($value, 'number');
1053  
1054 Example of valid values:
1055  
1056 '1'
1057 '123'
1058 '123.456'
1059 '-1'
1060 '-100'
1061 '-100.789'
1062  
1063 Example of invalid values:
1064  
1065 'a';
1066 '1.a';
1067 'a.1';
1068  
1069 You can also specify decimal part max digits using C<decimal_part_max> option.
1070  
1071 my $is_valid = $vc->check($value, 'number', {decimal_part_max => 3});
1072  
1073 Example of valid values:
1074  
1075 '123'
1076 '123.456'
1077 '-100.789'
1078  
1079 Example of invalid values:
1080  
1081 '123.4567'
1082 '-100.7891'
1083  
1084 =head2 ascii_graphic
1085  
1086 Check if the value is Ascii graphic characters(hex 21-7e).
1087 Generally, C<ascii_graphic> function is used to
1088 check the characters of a password.
1089
1090 my $is_valid = $vc->check($value, 'ascii');
1091  
1092 Example of valid values:
1093  
1094 "Ken!@-"
1095  
1096 Example of invalid values:
1097
1098 "aa aa"
1099 "\taaa"
1100  
1101 =head2 in
1102  
1103 Check if the value is one of the given values.
1104
1105 my $value = '001';
1106 my $is_valid = $vc->check($value, 'in', ['001', '002', '003']);
1107  
1108 Example of valid values:
1109  
1110 '001'
1111 '002'
1112 '003'
1113  
1114 Example of invalid values:
1115  
1116 '004'
1117 '005'
1118  
1119 =head1 Filtering functions
1120  
1121 L<Validator::Custom> have the following default filtering functions.
1122 You can call any filtering function using C<filter> method.
1123  
1124 =head2 trim
1125  
1126 Trim leading and trailing white space.
1127 Note that trim function remove unicode space character, not only C<[ \t\n\r\f]>.
1128  
1129 my $new_value = $vc->filter($value, 'trim');
1130  
1131 Filtering example:
1132  
1133 Input : '  Ken '
1134 Output: 'Ken'
1135  
1136 =head2 remove_blank
1137  
1138 Remove blank character and undefined value from array reference.
1139  
1140 my $new_values = $vc->filter($values, 'remove_blank');
1141  
1142 Filtering example:
1143  
1144 Input : [1, 2, '', undef, 4]
1145 Output: [1, 2, 4]
1146  
1147 =head1 Methods
1148  
1149 L<Validator::Custom> inherits all methods from L<Object::Simple>
1150 and implements the following new ones.
1151  
1152 =head2 new
1153  
1154 Create a new L<Validator::Custom> object.
1155  
1156 my $vc = Validator::Custom->new;
1157  
1158 =head2 add_check
1159  
1160 Add a checking function.
1161  
1162 $vc->add_check(int => sub { ... });
1163  
1164 Example:
1165
1166 $vc->add_check(
1167 int => sub {
1168 my ($vc, $value, $arg) = @_;
1169
1170 my $is_valid = $value =~ /^\-?[\d]+$/;
1171
1172 return $is_valid;
1173 }
1174 );
1175  
1176 Checking function receives three arguments,
1177 First argument is L<Validator::Custom> object,
1178 Second argument is the value for checking,
1179 Third argument is the argument of checking function.
1180  
1181 Your Checking function must return true or false value.
1182  
1183 =head2 add_filter
1184  
1185 Add a filtering function.
1186  
1187 $vc->add_filter(trim => sub { ... });
1188  
1189 Example:
1190  
1191 $vc->add_filter(
1192 trim => sub {
1193 my ($vc, $value, $arg) = @_;
1194
1195 $value =~ s/^\s+//;
1196 $value =~ s/\s+$//;
1197
1198 return $value;
1199 }
1200 );
1201  
1202 =head2 check
1203  
1204 Execute a checking function.
1205  
1206 my $is_valid = $vc->check($value, 'int');
1207 my $is_valid = $vc->check($value, 'int', $arg);
1208  
1209 First argument is the value for checking.
1210 Second argument is the name of the checking funcion.
1211 Third argument is the argument of the checking function.
1212  
1213 =head2 check_each
1214  
1215 Execute a checking function to all elements of array reference.
1216 If more than one element is invalid, C<check_each> method return false.
1217  
1218 my $is_valid = $vc->check_each($values, 'int');
1219 my $is_valid = $vc->check_each($values, 'int', $arg);
1220  
1221 First argument is the values for checking, which must be array reference.
1222 Second argument is the name of the checking funcion.
1223 Third argument is the argument of the checking function.
1224  
1225 =head2 filter
1226  
1227 Execute a filtering function.
1228  
1229 my $new_value = $vc->filter($value, 'trim');
1230 my $new_value = $vc->filter($value, 'trim', $arg);
1231  
1232 First argument is the value for filtering.
1233 Second argument is the name of the filtering funcion.
1234 Third argument is the argument of the filtering function.
1235  
1236 =head2 filter_each
1237  
1238 Execute a filtering function to all elements of array reference.
1239  
1240 my $new_values = $vc->filter_each($values, 'trim');
1241 my $new_values = $vc->filter_each($values, 'trim', $arg);
1242  
1243 First argument is the values for filtering, which must be array reference.
1244 Second argument is the name of the filtering funcion.
1245 Third argument is the argument of the filtering function.
1246  
1247 =head1 EXAMPLES
1248  
1249 Show you some examples to do some validation.
1250  
1251 Password checking:
1252
1253 my $password = 'abc';
1254 my $password2 = 'abc';
1255
1256 my $validation = $vc->validation;
1257
1258 if (!length $password) {
1259 $validation->add_failed(password => 'password must have length');
1260 }
1261 elsif (!$vc->check($password, 'ascii')) {
1262 $validation->add_failed(password => 'password contains invalid characters');
1263 }
1264 elsif ($password ne $password2) {
1265 $validation->add_failed(password => "two passwords don't match");
1266 }
1267
1268 if ($validation->is_valid) {
1269 # ...
1270 }
1271 else {
1272 # ...
1273 }
1274  
1275 Check box, selected at least 1, one of the given values:
1276  
1277 my $favorite = ['001', '002'];
1278  
1279 my $validation = $vc->validation;
1280
1281 if (@$favorite == 0) {
1282 $validation->add_failed(favorite => 'favorite must be selected at least 1');
1283 }
1284 elsif (!$vc->check($favorite, 'in', ['001', '002', '003'])) {
1285 $validation->add_failed(favorite => 'favorite have invalid value');
1286 }
1287
1288 if ($validtion->is_valid) {
1289 # ...
1290 }
1291 else {
1292 # ...
1293 }
1294  
1295 Convert date string to L<Time::Piece> object.
1296  
1297 my $date = '2014/05/16';
1298
1299 my $validation = $vc->validation;
1300
1301 my $date_tp;
1302 if (!length $date) {
1303 $validation->add_failed(date => 'date must have length');
1304 }
1305 else {
1306 eval { $date_tp = Time::Piece->strptime($date, '%Y/%m/%d') };
1307 if (!$date_tp) {
1308 $validation->add_failed(date => 'date value is invalid');
1309 }
1310 }
1311  
1312 Convert datetime string to L<Time::Piece> object.
1313  
1314 my $datetime = '2014/05/16 12:30:40';
1315
1316 my $validation = $vc->validation;
1317
1318 my $datetime_tp;
1319 if (!length $datetime) {
1320 $validation->add_failed(datetime => 'datetime must have length');
1321 }
1322 else {
1323 eval { $datetime_tp = Time::Piece->strptime($datetime, '%Y/%m/%d %H:%M:%S') };
1324 if (!$datetime_tp) {
1325 $validation->add_failed(datetime => 'datetime value is invalid');
1326 }
1327 }
1328  
1329 =head1 FAQ
1330  
1331 =head2 I use Validator::Custom 0.xx yet. I want to see documentation of Version 0.xx.
1332  
1333 See L<Validator::Custom::Document::Version0>.
1334 This is complete document for L<Validator::Custom> version 0.xx.
1335  
1336 =head2 What point I take care of in Version 1.xx.
1337  
1338 =over 4
1339  
1340 =item *
1341  
1342 C<in_array> constraint function is renamed to C<in> checking function.
1343  
1344 =item *
1345  
1346 C<trim> filtering function becomes triming unicode space characters, not only C<[ \t\n\r\f]>.
1347  
1348 =item *
1349  
1350 C<decimal> constraint is renamed to C<number> checking function and simplified.
1351  
1352 =item *
1353  
1354 C<date_to_timepiece> checking function doesn't exist.
1355 About alternative way, see the topic "Convert date string to Time::Piece object" in "EXAMPLES".
1356  
1357 =item *
1358  
1359 C<datetime_to_timepiece> checking function doesn't exists.
1360 About alternative way, see the topic "Convert datetime string to Time::Piece object" in "EXAMPLES".
1361  
1362 =back
1363  
1364 =head2 How to create the corresponding checking functions in Version 0.xx constraint functions.
1365  
1366 I show some examples.
1367  
1368 space
1369  
1370 $vc->add_check(space => sub {
1371 my ($vc, $value, $arg) = @_;
1372 return defined $value && $value =~ '^[ \t\n\r\f]*$' ? 1 : 0;
1373 });
1374  
1375 http_url
1376  
1377 $vc->add_check(http_url => sub {
1378 my ($vc, $value, $arg) = @_;
1379 return defined $value && $value =~ /^s?https?:\/\/[-_.!~*'()a-zA-Z0-9;\/?:\@&=+\$,%#]+$/ ? 1 : 0;
1380 });
1381  
1382 decimal
1383  
1384 $vc->add_check(decimal => sub {
1385 my ($vc, $value, $arg) = @_;
1386  
1387 return undef unless defined $value;
1388
1389 my $digits_tmp = $arg;
1390
1391 # Digit
1392 my $digits;
1393 if (defined $digits_tmp) {
1394 if (ref $digits_tmp eq 'ARRAY') {
1395 $digits = $digits_tmp;
1396 }
1397 else {
1398 $digits = [$digits_tmp, undef];
1399 }
1400 }
1401 else {
1402 $digits = [undef, undef];
1403 }
1404
1405 # Regex
1406 my $re;
1407 if (defined $digits->[0] && defined $digits->[1]) {
1408 $re = qr/^[0-9]{1,$digits->[0]}(\.[0-9]{0,$digits->[1]})?$/;
1409 }
1410 elsif (defined $digits->[0]) {
1411 $re = qr/^[0-9]{1,$digits->[0]}(\.[0-9]*)?$/;
1412 }
1413 elsif (defined $digits->[1]) {
1414 $re = qr/^[0-9]+(\.[0-9]{0,$digits->[1]})?$/;
1415 }
1416 else {
1417 $re = qr/^[0-9]+(\.[0-9]*)?$/;
1418 }
1419
1420 # Check value
1421 if ($value =~ /$re/) {
1422 return 1;
1423 }
1424 else {
1425 return 0;
1426 }
1427 }
1428  
1429 =head2 How to create the corresponding filtering functions in Version 0.xx constraint functions.
1430  
1431 I show some examples.
1432  
1433 trim_collapse
1434  
1435 $vc->add_filter(trim_collapse => sub {
1436 my ($vc, $value, $arg) = @_;
1437
1438 return undef unless defined $value;
1439
1440 $value =~ s/[ \t\n\r\f]+/ /g;
1441 $value =~ s/^[ \t\n\r\f]*(.*?)[ \t\n\r\f]*$/$1/ms;
1442  
1443 return $value;
1444 });
1445  
1446 trim_lead
1447  
1448 $vc->add_filter(trim_lead => sub {
1449 my ($vc, $value, $arg) = @_;
1450
1451 return undef unless defined $value;
1452  
1453 $value =~ s/^[ \t\n\r\f]+(.*)$/$1/ms;
1454  
1455 return $value;
1456 });
1457  
1458 trim_trail
1459  
1460 $vc->add_filter(trim_trail => sub {
1461 my ($vc, $value, $arg) = @_;
1462
1463 return undef unless defined $value;
1464  
1465 $value =~ s/^(.*?)[ \t\n\r\f]+$/$1/ms;
1466  
1467 return $value;
1468 });
1469  
1470 trim_uni
1471  
1472 $vc->add_filter(trim_uni => sub {
1473 my ($vc, $value, $arg) = @_;
1474
1475 return undef unless defined $value;
1476  
1477 $value =~ s/^\s*(.*?)\s*$/$1/ms;
1478  
1479 return $value;
1480 });
1481  
1482 trim_uni_collapse
1483  
1484 $vc->add_filter(trim_uni_collapse => sub {
1485 my ($vc, $value, $arg) = @_;
1486  
1487 return undef unless defined $value;
1488
1489 $value =~ s/\s+/ /g;
1490 $value =~ s/^\s*(.*?)\s*$/$1/ms;
1491  
1492 return $value;
1493 });
1494  
1495 trim_uni_lead
1496  
1497 $vc->add_filter(trim_uni_lead => sub {
1498 my ($vc, $value, $arg) = @_;
1499
1500 return undef unless defined $value;
1501
1502 $value =~ s/^\s+(.*)$/$1/ms;
1503
1504 return $value;
1505 });
1506  
1507 trim_uni_trail
1508  
1509 $vc->add_filter(trim_uni_trail => sub {
1510 my ($vc, $value, $arg) = @_;
1511
1512 return undef unless defined $value;
1513  
1514 $value =~ s/^(.*?)\s+$/$1/ms;
1515  
1516 return $value;
1517 });
1518  
1519 =head1 AUTHOR
1520  
1521 Yuki Kimoto, C<< <kimoto.yuki at gmail.com> >>
1522  
1523 L<http://github.com/yuki-kimoto/Validator-Custom>
1524  
1525 =head1 COPYRIGHT & LICENCE
1526  
1527 Copyright 2009-2017 Yuki Kimoto, all rights reserved.
1528  
1529 This program is free software; you can redistribute it and/or modify it
1530 under the same terms as Perl itself.
1531  
1532 =cut
↑ Summary Custom/Constraint.pm »