LIVR.pm

filter: Statementstmt 98.4% 195 / 198 Branchbran 86.7% 59 / 68 Conditioncond 65.6% 21 / 32 MC/DCmcdc 33.3% 7 / 21 Subroutinesub 97.1% 34 / 35 Podpod 100% 11 / 11 totaltotal 89.5% 327 / 365 CC 54 SCAR 17.4
CC
54
Cov
92%
validate
16.0
_auto_trim
7.1
_field_rule
6.0
CRAP 5.7
« LIVR/Rules/Meta.pm ↑ Summary LIVR/Rules/Format.pm »
1 package Validator::LIVR;
2  
3 10 ▶use v5.10;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 10 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 10 ▶use Carp qw/croak/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 10 ▶use Validator::LIVR::Rules::Common;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 10 ▶use Validator::LIVR::Rules::String;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 10 ▶use Validator::LIVR::Rules::Numeric;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use Validator::LIVR::Rules::Special;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use Validator::LIVR::Rules::Meta;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 10 ▶use Validator::LIVR::Rules::Modifiers;
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 10 our $VERSION = '2.22';
17  
18 # Rule builders of new validators. The hash is never changed in place: register_default_rules()
19 # makes a new one. So new() does not copy it, and a validator keeps the rules of the time it
20 # was created
21 10 my $DEFAULT_RULES = {
22 'required' => \&Validator::LIVR::Rules::Common::required,
23 'not_empty' => \&Validator::LIVR::Rules::Common::not_empty,
24 'not_empty_list' => \&Validator::LIVR::Rules::Common::not_empty_list,
25 'any_object' => \&Validator::LIVR::Rules::Common::any_object,
26  
27 'one_of' => \&Validator::LIVR::Rules::String::one_of,
28 'min_length' => \&Validator::LIVR::Rules::String::min_length,
29 'max_length' => \&Validator::LIVR::Rules::String::max_length,
30 'length_equal' => \&Validator::LIVR::Rules::String::length_equal,
31 'length_between' => \&Validator::LIVR::Rules::String::length_between,
32 'like' => \&Validator::LIVR::Rules::String::like,
33 'string' => \&Validator::LIVR::Rules::String::string,
34 'eq' => \&Validator::LIVR::Rules::String::equal,
35  
36 'integer' => \&Validator::LIVR::Rules::Numeric::integer,
37 'positive_integer' => \&Validator::LIVR::Rules::Numeric::positive_integer,
38 'decimal' => \&Validator::LIVR::Rules::Numeric::decimal,
39 'positive_decimal' => \&Validator::LIVR::Rules::Numeric::positive_decimal,
40 'max_number' => \&Validator::LIVR::Rules::Numeric::max_number,
41 'min_number' => \&Validator::LIVR::Rules::Numeric::min_number,
42 'number_between' => \&Validator::LIVR::Rules::Numeric::number_between,
43  
44 'email' => \&Validator::LIVR::Rules::Special::email,
45 'equal_to_field' => \&Validator::LIVR::Rules::Special::equal_to_field,
46 'url' => \&Validator::LIVR::Rules::Special::url,
47 'iso_date' => \&Validator::LIVR::Rules::Special::iso_date,
48  
49 'nested_object' => \&Validator::LIVR::Rules::Meta::nested_object,
50 'variable_object' => \&Validator::LIVR::Rules::Meta::variable_object,
51 'list_of' => \&Validator::LIVR::Rules::Meta::list_of,
52 'list_of_objects' => \&Validator::LIVR::Rules::Meta::list_of_objects,
53 'or' => \&Validator::LIVR::Rules::Meta::livr_or,
54 'list_of_different_objects' => \&Validator::LIVR::Rules::Meta::list_of_different_objects,
55  
56  
57 'trim' => \&Validator::LIVR::Rules::Modifiers::trim,
58 'to_lc' => \&Validator::LIVR::Rules::Modifiers::to_lc,
59 'to_uc' => \&Validator::LIVR::Rules::Modifiers::to_uc,
60 'remove' => \&Validator::LIVR::Rules::Modifiers::remove,
61 'leave_only' => \&Validator::LIVR::Rules::Modifiers::leave_only,
62 'default' => \&Validator::LIVR::Rules::Modifiers::default,
63  
64 # LIVR 2.5, loaded on first use
65 'boolean' => _lazy_rule( Types => 'boolean' ),
66 'not_one_of' => _lazy_rule( Types => 'not_one_of' ),
67 'max_decimals' => _lazy_rule( Types => 'max_decimals' ),
68 'digits' => _lazy_rule( Types => 'digits' ),
69 'starts_with' => _lazy_rule( Types => 'starts_with' ),
70 'ends_with' => _lazy_rule( Types => 'ends_with' ),
71 'contains' => _lazy_rule( Types => 'contains' ),
72 'any' => _lazy_rule( Types => 'any' ),
73  
74 'iso_datetime' => _lazy_rule( DateTime => 'iso_datetime' ),
75 'iso_time' => _lazy_rule( DateTime => 'iso_time' ),
76  
77 'required_if' => _lazy_rule( Conditional => 'required_if' ),
78 'when' => _lazy_rule( Conditional => 'when' ),
79  
80 'values' => _lazy_rule( Collection => 'livr_values' ),
81 'keys' => _lazy_rule( Collection => 'livr_keys' ),
82 'list_length' => _lazy_rule( Collection => 'list_length' ),
83 'unique' => _lazy_rule( Collection => 'unique' ),
84 'split' => _lazy_rule( Collection => 'livr_split' ),
85  
86 'uuid' => _lazy_rule( Format => 'uuid' ),
87 'ip' => _lazy_rule( Format => 'ip' ),
88 'cidr' => _lazy_rule( Format => 'cidr' ),
89 'hostname' => _lazy_rule( Format => 'hostname' ),
90 'base64' => _lazy_rule( Format => 'base64' ),
91 'hex' => _lazy_rule( Format => 'livr_hex' ),
92 'digest' => _lazy_rule( Format => 'digest' ),
93 'mongo_id' => _lazy_rule( Format => 'mongo_id' ),
94 'hex_color' => _lazy_rule( Format => 'hex_color' ),
95 'mac' => _lazy_rule( Format => 'mac' ),
96 'e164' => _lazy_rule( Format => 'e164' ),
97 'semver' => _lazy_rule( Format => 'semver' ),
98 'jwt' => _lazy_rule( Format => 'jwt' ),
99 'luhn' => _lazy_rule( Format => 'luhn' ),
100 'credit_card' => _lazy_rule( Format => 'credit_card' ),
101 'iban' => _lazy_rule( Format => 'iban' ),
102 };
103  
104 10 my $IS_DEFAULT_AUTO_TRIM = 0;
105  
106 # A rule builder that loads the module of the rule on first use. A schema uses a few of the
107 # LIVR 2.5 rules, and loading all of them would make "use Validator::LIVR" twice as slow
108 330 ▶sub _lazy_rule {
Subroutine _lazy_rule: called CC=1 SCAR=0.0
109 330 my ( $module, $name ) = @_;
110 330 my $file = "Validator/LIVR/Rules/$module.pm";
111 330 my $builder;
112  
113 2006 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
114 2006 ▶ $builder ||= do {
Condition66%2/3
$builder ||= do { require $file; no strict 'refs'; \&{"Validator::LIVR::Rules::${module}::$name";} }
l!l&&r!l&&!r
1956500
MC/DC0%0/2
$builder ||= do { require $file; no strict 'refs'; \&{"Validator::LIVR::Rules::${module}::$name";} }
$builder do { require $file; no strict 'refs'; \&{"Validator::LIVR::Rules::${module}::$name";} }
Truth table66%2/3
A ||= B
A= $builderB= do { require $file; no strict 'refs'; \&{"Validator::LIVR::Rules::${module}::$name";} }
ABresult
1X1
011
000
115 50 require $file;
116 10 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
117 50 \&{"Validator::LIVR::Rules::${module}::$name"};
118 };
119  
120 2006 goto &$builder;
121 330 };
122 }
123  
124 1102 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod documented
125 1102 my ($class, $livr_rules, $is_auto_trim) = @_;
126  
127 1102 ▶ my $self = bless {
Condition66%2/3
$is_auto_trim // $IS_DEFAULT_AUTO_TRIM
l!l&&r!l&&!r
2710750
MC/DC0%0/2
$is_auto_trim // $IS_DEFAULT_AUTO_TRIM
$is_auto_trim $IS_DEFAULT_AUTO_TRIM
Truth table66%2/3
A // B
A= $is_auto_trimB= $IS_DEFAULT_AUTO_TRIM
ABresult
1X1
011
000
128 is_prepared => 0,
129 livr_rules => $livr_rules,
130 validators => {},
131 validator_builders => $DEFAULT_RULES, # copied by the first register_rules()
132 is_builders_shared => 1,
133 errors => undef,
134 is_auto_trim => ( $is_auto_trim // $IS_DEFAULT_AUTO_TRIM )
135 }, $class;
136  
137 1102 return $self;
138 }
139  
140 5 ▶sub register_default_rules {
Subroutine register_default_rules: called CC=3 SCAR=11.0
Pod documented
141 5 my ( $class, %rules ) = @_;
142  
143 5 my %default_rules = %$DEFAULT_RULES;
144 5 foreach my $rule_name ( keys %rules ) {
145 141 my $rule_builder = $rules{$rule_name};
146 141 ▶ croak "RULE_BUILDER [$rule_name] SHOULD BE A CODEREF" unless ref($rule_builder) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rule_builder eq "CODE" 0 141 141
147  
148 141 $default_rules{$rule_name} = $rule_builder;
149 }
150 5 $DEFAULT_RULES = \%default_rules;
151  
152 5 return $class;
153 }
154  
155 1 ▶sub register_aliased_default_rule {
Subroutine register_aliased_default_rule: called CC=2 SCAR=7.0
Pod documented
156 1 my ( $class, $alias ) = @_;
157  
158 1 ▶ die 'Alias name required' unless $alias->{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $alias->{"name"} 0 1 1
159 1 $DEFAULT_RULES = { %$DEFAULT_RULES, $alias->{name} => $class->_build_aliased_rule($alias) };
160  
161 1 return $class;
162 }
163  
164 3 ▶sub get_default_rules {
Subroutine get_default_rules: called CC=1 SCAR=0.0
Pod documented
165 3 return {%$DEFAULT_RULES};
166 }
167  
168 0 ▶sub default_auto_trim {
Subroutine default_auto_trim: not called CC=1 SCAR=6.9
Pod documented
169 0 my ($class, $is_auto_trim) = @_;
170 0 $IS_DEFAULT_AUTO_TRIM = !!$is_auto_trim;
171 }
172  
173 1104 ▶sub prepare {
Subroutine prepare: called CC=4 SCAR=13.9
Pod documented
174 1104 my $self = shift;
175  
176 1104 my $all_rules = $self->{livr_rules};
177  
178 # Rule builders get the hash, and metarules give it to their validators: a later
179 # register_rules() copies it
180 1104 my $rule_builders = $self->{validator_builders};
181 1104 $self->{is_builders_shared} = 1;
182  
183 # Not "each": when a rule dies, it leaves the iterator in the middle of the hash,
184 # and the next prepare() would skip the fields up to that rule
185 1104 foreach my $field ( keys %$all_rules ) {
186 3782 my $field_rules = $all_rules->{$field};
187 3782 ▶ $field_rules = [$field_rules] if ref($field_rules) ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $field_rules ne "ARRAY" 3126 656 3782
188  
189 3782 my @validators;
190 3782 foreach my $rule (@$field_rules) {
191 4227 my ($name, $args) = $self->_parse_rule($rule);
192 4222 push @validators, $self->_build_validator($name, $args, $rule_builders);
193 }
194 3549 $self->{validators}{$field} = \@validators;
195 }
196  
197 871 $self->{is_prepared} = 1;
198  
199 871 return $self;
200 }
201  
202 493 ▶sub validate {
Subroutine validate: called CC=16 SCAR=27.7
Pod documented
203 493 my ($self, $data) = @_;
204 493 ▶ $self->prepare() unless $self->{is_prepared};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"is_prepared"} 223 270 493
205  
206 489 ▶ if ( ref($data) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH") 1 488 489
207 1 $self->{errors} = 'FORMAT_ERROR';
208 1 return;
209 }
210  
211 488 ▶ $data = $self->_auto_trim($data) if $self->{is_auto_trim};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"is_auto_trim"} 2 486 488
212  
213 488 my ( %errors, %result );
214 488 my $all_validators = $self->{validators};
215  
216 488 foreach my $field_name ( keys %$all_validators ) {
217 2914 my $validators = $all_validators->{$field_name};
218 2914 ▶ next unless $validators && @$validators;
Branch: 1 branch
BranchTrueFalseTotal
unless $validators and @$validators 0 2914 2914
Condition33%1/3
$validators and @$validators
!ll&&!rl&&r
002914
MC/DC0%0/2
$validators and @$validators
$validators @$validators
Truth table33%1/3
A and B
A= $validatorsB= @$validators
ABresult
0X0
100
111
219  
220 2914 my $value = $data->{$field_name};
221  
222 # The output of the previous rules, the same as $result{$field_name}
223 2914 my ( $has_output, $output );
224  
225 2914 foreach my $v_cb (@$validators) {
226 3105 ▶ my $field_result = $output // $value;
Condition100%3/3
$output // $value
l!l&&r!l&&!r
1812644280
MC/DC100%2/2
$output // $value
$output $value
Truth table100%3/3
A // B
A= $outputB= $value
ABresult
1X1
011
000
227  
228 3105 ▶ my $err_code = $v_cb->( $has_output ? $output : $value, $data, \$field_result );
Branch: 1 branch
BranchTrueFalseTotal
$has_output ? : 186 2919 3105
229  
230 3105 ▶ if ( $err_code ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($err_code) { } 1408 1697 3105
elsif (defined $field_result) { } 1500 197 1697
elsif (not $has_output and exists $data->{$field_name}) { } 79 120 199
231 1408 $errors{$field_name} = $err_code;
232 1408 $has_output = 0;
233 1408 last;
234 } elsif ( defined($field_result) ) {
235 1500 ( $has_output, $output ) = ( 1, $field_result );
236 ▶ } elsif ( !$has_output && exists $data->{$field_name} ) {
Condition100%3/3
not $has_output and exists $data->{$field_name}
!ll&&!rl&&r
211679
MC/DC100%2/2
not $has_output and exists $data->{$field_name}
not $has_output exists $data->{$field_name}
Truth table100%3/3
not(A) and B
A= not $has_outputB= exists $data->{$field_name}
ABresult
0X0
100
111
237 79 ( $has_output, $output ) = ( 1, undef );
238 }
239 }
240  
241 2914 ▶ $result{$field_name} = $output if $has_output;
Branch: 1 branch
BranchTrueFalseTotal
if $has_output 1395 1519 2914
242 }
243  
244 488 ▶ if ( keys %errors ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %errors) { } 229 259 488
245 229 $self->{errors} = \%errors;
246 229 return;
247 } else {
248 259 $self->{errors} = undef;
249 259 return \%result;
250 }
251 }
252  
253 445 ▶sub get_errors {
Subroutine get_errors: called CC=1 SCAR=0.0
Pod documented
254 445 my $self = shift;
255 445 return $self->{errors};
256 }
257  
258 7 ▶sub register_rules {
Subroutine register_rules: called CC=5 SCAR=16.2
Pod documented
259 7 my ( $self, %rules ) = @_;
260  
261 7 my $builders = $self->{validator_builders};
262  
263 7 foreach my $rule_name ( keys %rules ) {
264 78 my $rule_builder = $rules{$rule_name};
265 78 ▶ croak "RULE_BUILDER [$rule_name] SHOULD BE A CODEREF" unless ref($rule_builder) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $rule_builder eq "CODE" 0 78 78
266  
267 # Metarules register all rules of their validator, usually the same ones
268 78 ▶ next if $builders->{$rule_name} && $builders->{$rule_name} == $rule_builder;
Branch: 1 branch
BranchTrueFalseTotal
if $builders->{$rule_name} and $builders->{$rule_name} == $rule_builder 69 9 78
Condition66%2/3
$builders->{$rule_name} and $builders->{$rule_name} == $rule_builder
!ll&&!rl&&r
9069
MC/DC50%1/2
$builders->{$rule_name} and $builders->{$rule_name} == $rule_builder
$builders->{$rule_name} $builders->{$rule_name} == $rule_builder
Truth table66%2/3
A and B
A= $builders->{$rule_name}B= $builders->{$rule_name} == $rule_builder
ABresult
0X0
100
111
269  
270 9 $builders = $self->_own_builders();
271 9 $builders->{$rule_name} = $rule_builder;
272 }
273  
274 7 return $self;
275 }
276  
277 53 ▶sub register_aliased_rule {
Subroutine register_aliased_rule: called CC=2 SCAR=7.0
Pod documented
278 53 my ( $self, $alias ) = @_;
279  
280 53 ▶ die 'Alias name required' unless $alias->{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $alias->{"name"} 0 53 53
281 53 $self->_own_builders()->{ $alias->{name} } = $self->_build_aliased_rule($alias);
282  
283 53 return $self;
284 }
285  
286 2 ▶sub get_rules {
Subroutine get_rules: called CC=1 SCAR=0.0
Pod documented
287 2 my $self = shift;
288  
289 2 return { %{$self->{validator_builders}} };
290 }
291  
292 # The rule builders of the validator, copied if they are shared with other validators
293 62 ▶sub _own_builders {
Subroutine _own_builders: called CC=2 SCAR=6.9
294 62 my $self = shift;
295  
296 62 ▶ if ( $self->{is_builders_shared} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"is_builders_shared"}) 33 29 62
297 33 $self->{validator_builders} = { %{ $self->{validator_builders} } };
298 33 $self->{is_builders_shared} = 0;
299 }
300  
301 62 return $self->{validator_builders};
302 }
303  
304 # For metarules: a validator with the rules of the validator that builds it, as
305 # new($livr_rules)->register_rules(%$rule_builders), without copying the rules
306 660 ▶sub _new_with_rules {
Subroutine _new_with_rules: called CC=1 SCAR=0.0
307 660 my ( $class, $livr_rules, $rule_builders, $is_auto_trim ) = @_;
308  
309 660 my $self = $class->new( $livr_rules, $is_auto_trim );
310 660 $self->{validator_builders} = $rule_builders;
311  
312 660 return $self;
313 }
314  
315 # All rules of a field as one rule, sub { my ($value, $all_values, $output_ref) = @_; ... },
316 # that applies them as validate() does. It returns the first error, or sets the output. The
317 # caller sets $$output_ref to the value before the call. Metarules and aliases validate values
318 # with it: without the hashes of validate(), and with $all_values of their caller
319 694 ▶sub _field_rule {
Subroutine _field_rule: called CC=6 SCAR=18.0
320 694 my ( $self, $field_name ) = @_;
321 694 ▶ $self->prepare() unless $self->{is_prepared};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"is_prepared"} 259 435 694
322  
323 685 ▶ my $validators = $self->{validators}{$field_name} || [];
Condition50%1/2
$self->{'validators'}{$field_name} || []
l!l
6850
MC/DC0%0/1
$self->{'validators'}{$field_name} || []
$self->{'validators'}{$field_name}
Truth table50%1/2
A
A= $self->{'validators'}{$field_name}
Aresult
11
00
324 685 my $is_auto_trim = $self->{is_auto_trim};
325  
326 # A field without rules is not in the output of validate()
327 685 ▶ return sub { ${ $_[2] } = undef; return } if !@$validators;
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless @$validators 1 684 685
328  
329 684 ▶ return $validators->[0] if @$validators == 1 && !$is_auto_trim;
Branch: 1 branch
BranchTrueFalseTotal
if @$validators == 1 and not $is_auto_trim 517 167 684
Condition66%2/3
@$validators == 1 and not $is_auto_trim
!ll&&!rl&&r
1670517
MC/DC50%1/2
@$validators == 1 and not $is_auto_trim
@$validators == 1 not $is_auto_trim
Truth table66%2/3
A and not(B)
A= @$validators == 1B= not $is_auto_trim
ABresult
0X0
100
111
330  
331 157 ▶ return sub {
Subroutine __ANON__: called CC=5 SCAR=16.1
332 157 my ( $value, $all_values, $output_ref ) = @_;
333 157 ▶ $value = $self->_auto_trim($value) if $is_auto_trim;
Branch: 1 branch
BranchTrueFalseTotal
if $is_auto_trim 0 157 157
334  
335 157 foreach my $v_cb (@$validators) {
336 288 my $result = $value;
337 288 my $err_code = $v_cb->( $value, $all_values, \$result );
338 288 ▶ return $err_code if $err_code;
Branch: 1 branch
BranchTrueFalseTotal
if $err_code 70 218 288
339  
340 218 ▶ $value = $result if defined $result;
Branch: 1 branch
BranchTrueFalseTotal
if defined $result 214 4 218
341 }
342  
343 87 $$output_ref = $value;
344 87 return;
345 167 };
346 }
347  
348 4227 ▶sub _parse_rule {
Subroutine _parse_rule: called CC=4 SCAR=13.9
349 4227 my ($self, $livr_rule) = @_;
350  
351 4227 my ($name, $args);
352  
353 4227 ▶ if ( ref($livr_rule) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $livr_rule eq 'HASH') { } 1998 2229 4227
354 # Only the first key would be used, and the order of keys is random
355 1998 my @names = sort keys %$livr_rule;
356 1998 ▶ die 'Rule [' . join( ', ', @names ) . "] should have one name\n" if @names != 1;
Branch: 1 branch
BranchTrueFalseTotal
if @names != 1 5 1993 1998
357  
358 1993 $name = $names[0];
359 1993 $args = $livr_rule->{$name};
360 1993 ▶ $args = [$args] unless ref($args) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "ARRAY" 1289 704 1993
361 } else {
362 2229 $name = $livr_rule;
363 2229 $args = [];
364 }
365  
366 4222 return ($name, $args);
367 }
368  
369 4222 ▶sub _build_validator {
Subroutine _build_validator: called CC=3 SCAR=11.2
370 4222 my ($self, $name, $args, $rule_builders) = @_;
371 4222 ▶ $rule_builders //= $self->{validator_builders};
Condition33%1/3
$rule_builders //= $self->{"validator_builders"}
l!l&&r!l&&!r
422200
MC/DC0%0/2
$rule_builders //= $self->{"validator_builders"}
$rule_builders $self->{"validator_builders"}
Truth table33%1/3
A //= B
A= $rule_buildersB= $self->{"validator_builders"}
ABresult
1X1
011
000
372  
373 4222 my $rule_builder = $rule_builders->{$name};
374 4222 ▶ die "Rule [$name] not registered\n" unless $rule_builder;
Branch: 1 branch
BranchTrueFalseTotal
unless $rule_builder 12 4210 4222
375  
376 4210 return $rule_builder->( @$args, $rule_builders );
377 }
378  
379 54 ▶sub _build_aliased_rule {
Subroutine _build_aliased_rule: called CC=3 SCAR=11.0
380 54 my ($class, $alias) = @_;
381  
382 54 ▶ die 'Alias name required' unless $alias->{name};
Branch: 1 branch
BranchTrueFalseTotal
unless $alias->{"name"} 0 54 54
383 54 ▶ die 'Alias rules required' unless $alias->{rules};
Branch: 1 branch
BranchTrueFalseTotal
unless $alias->{"rules"} 0 54 54
384  
385 54 my $livr = { value => $alias->{rules} };
386 54 my $error = $alias->{error};
387  
388 117 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
389 117 my $rule_builders = $_[-1];
390 117 my $field_rule = __PACKAGE__->_new_with_rules( $livr, $rule_builders )->_field_rule('value');
391  
392 # Aliases are transparent: their rules see the fields next to the field that uses the alias
393 126 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
394 126 my ($value, $all_values, $output_ref) = @_;
395  
396 126 my $output = $value;
397 126 ▶ if ( my $err_code = $field_rule->( $value, $all_values, \$output ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err_code = &$field_rule($value, $all_values, \$output)) 50 76 126
398 50 ▶ return $error || $err_code;
Condition66%2/3
$error || $err_code
l!l&&r!l&&!r
15350
MC/DC0%0/2
$error || $err_code
$error $err_code
Truth table66%2/3
A || B
A= $errorB= $err_code
ABresult
1X1
011
000
399 }
400  
401 76 $$output_ref = $output;
402 76 return;
403 111 };
404 54 };
405 }
406  
407 13 ▶sub _auto_trim {
Subroutine _auto_trim: called CC=7 SCAR=19.6
408 13 my ( $self, $data ) = @_;
409 13 my $ref_type = ref($data);
410  
411 13 ▶ if ( !$ref_type && $data ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not $ref_type and $data) { } 8 5 13
elsif ($ref_type eq 'HASH') { } 4 1 5
elsif ($ref_type eq 'ARRAY') { } 1 0 1
Condition66%2/3
not $ref_type and $data
!ll&&!rl&&r
508
MC/DC50%1/2
not $ref_type and $data
not $ref_type $data
Truth table66%2/3
not(A) and B
A= not $ref_typeB= $data
ABresult
0X0
100
111
412 8 $data =~ s/^\s+//;
413 8 $data =~ s/\s+$//;
414 8 return $data;
415 }
416 elsif ( $ref_type eq 'HASH' ) {
417 4 my $trimmed_data = {};
418  
419 4 foreach my $key ( keys %$data ) {
420 9 $trimmed_data->{$key} = $self->_auto_trim( $data->{$key} );
421 }
422  
423 4 return $trimmed_data;
424 }
425 elsif ( $ref_type eq 'ARRAY' ) {
426 1 my $trimmed_data = [];
427  
428 1 ▶ for ( my $i = 0; $i < @$data; $i++ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($i < @$data) 2 1 3
429 2 $trimmed_data->[$i] = $self->_auto_trim( $data->[$i] )
430 }
431  
432 1 return $trimmed_data;
433 }
434  
435 0 return $data;
436 }
437  
438 10 1; # End of Validator::LIVR
439  
440 =for HTML <a href="https://github.com/koorchik/Validator-LIVR/actions/workflows/test.yml"><img src="https://github.com/koorchik/Validator-LIVR/actions/workflows/test.yml/badge.svg?branch=master" alt="Tests"></a>
441 <a href="https://metacpan.org/dist/Validator-LIVR"><img src="https://img.shields.io/cpan/v/Validator-LIVR.svg" alt="CPAN version"></a>
442  
443 =head1 NAME
444  
445 Validator::LIVR - Lightweight validator supporting Language Independent Validation Rules Specification (LIVR)
446  
447 =head1 SYNOPSIS
448  
449 use Validator::LIVR;
450  
451 my $validator = Validator::LIVR->new({
452 name => 'required',
453 email => [ 'required', 'email' ],
454 gender => { one_of => [ 'male', 'female' ] },
455 phone => { max_length => 10 },
456 password => [ 'required', { min_length => 10 } ],
457 password2 => { equal_to_field => 'password' },
458 });
459  
460 if ( my $valid_data = $validator->validate($user_data) ) {
461 save_user($valid_data);
462 } else {
463 my $errors = $validator->get_errors();
464 # { email => 'WRONG_EMAIL', password => 'TOO_SHORT' }
465 }
466  
467 =head1 DESCRIPTION
468  
469 LIVR rules are plain data: a hash that maps field names to rules. They are
470 easy to read, and because the same rules work in
471 L<a dozen languages|https://livr-spec.org/introduction/implementations.html>,
472 one rule set can check a form in the browser with JavaScript and again on the
473 server with Perl.
474  
475 This module implements L<LIVR 2.0|https://livr-spec.org> and
476 L<LIVR 2.5|https://github.com/koorchik/LIVR/blob/master/drafts/v2.5.md>, and
477 passes the test suites of both. The rules added in LIVR 2.5 are in
478 L</LIVR 2.5 rules>.
479  
480 =over 4
481  
482 =item * B<Declarative rules> that you can keep in JSON and share with other services.
483  
484 =item * B<All errors at once>, not just the first one.
485  
486 =item * B<Only described fields in the output.> A field without rules, such as an
487 unexpected C<is_admin>, never reaches your code.
488  
489 =item * B<Nested data>: objects, lists, lists of objects and objects of several types.
490  
491 =item * B<Error codes, not messages>, such as C<REQUIRED> or C<TOO_SHORT>. Turn them
492 into messages in any language you need.
493  
494 =item * B<Data cleanup> with modifiers, such as C<trim>, C<to_lc> and C<default>.
495  
496 =item * B<Your own rules>, as aliases of existing rules or as Perl code.
497  
498 =item * B<No dependencies>: only modules that come with Perl.
499  
500 =back
501  
502 Use it for user input, configs, API requests and responses, or any other data
503 that has to have a known shape.
504  
505 =head1 A QUICK TOUR
506  
507 =head2 Writing rules
508  
509 A rule set maps each field to its rules. A rule is written in one of these
510 ways:
511  
512 {
513 name => 'required', # a rule without arguments
514 bio => { max_length => 1000 }, # a rule with one argument
515 nick => { length_between => [ 3, 20 ] }, # a rule with several arguments
516 email => [ 'required', 'email' ], # several rules
517 }
518  
519 Several rules of a field are applied in order, and the field stops at its
520 first error. A hash is always one rule, so two rules with arguments are two
521 hashes: C<< [ { min_length => 3 }, { max_length => 20 } ] >>.
522  
523 Most rules accept empty values: C<undef> and the empty string. So a field is
524 optional until you add C<required>:
525  
526 {
527 age => 'positive_integer', # can be missing
528 id => [ 'required', 'positive_integer' ], # must be present
529 }
530  
531 =head2 Validating nested data
532  
533 Metarules describe the structure of the data, and errors have the same shape
534 as the data:
535  
536 my $validator = Validator::LIVR->new({
537 order_id => [ 'required', 'positive_integer' ],
538 address => [ 'required', { nested_object => {
539 country => [ 'required', { one_of => [ 'Ukraine', 'USA' ] } ],
540 city => 'required',
541 zip => 'positive_integer',
542 } } ],
543 products => [ 'required', 'not_empty_list', { list_of_objects => {
544 product_id => [ 'required', 'positive_integer' ],
545 quantity => [ 'required', { min_number => 1 } ],
546 } } ],
547 tags => { list_of => [ 'string', { max_length => 10 } ] },
548 });
549  
550 For an order with an unknown country, a second product with a quantity of 0
551 and a second tag that is too long, C<get_errors> returns:
552  
553 {
554 address => { country => 'NOT_ALLOWED_VALUE' },
555 products => [ undef, { quantity => 'TOO_LOW' } ],
556 tags => [ undef, 'TOO_LONG' ],
557 }
558  
559 =head2 Cleaning data
560  
561 Modifiers change the value for the next rules and for the output:
562  
563 my $validator = Validator::LIVR->new({
564 email => [ 'trim', 'required', 'email', 'to_lc' ],
565 phone => { leave_only => '0123456789' },
566 role => [ { default => 'user' }, { one_of => [ 'user', 'admin' ] } ],
567 });
568  
569 $validator->validate({ email => ' John@Example.COM ', phone => '+38 (050) 123-45-67' });
570 # { email => 'john@example.com', phone => '380501234567', role => 'user' }
571  
572 To trim every string of the input before validation, turn on auto trim for
573 one validator with C<< Validator::LIVR->new( $rules, 1 ) >>, or for all new
574 validators with C<< Validator::LIVR->default_auto_trim(1) >>.
575  
576 =head2 Sharing rules with other languages
577  
578 Rules are plain data, so they can live in a JSON file:
579  
580 {
581 "email": [ "required", "email" ],
582 "password": [ "required", { "min_length": 10 } ]
583 }
584  
585 use JSON::PP qw(decode_json);
586  
587 my $validator = Validator::LIVR->new( decode_json($json_rules) );
588  
589 The same file works with L<livr|https://www.npmjs.com/package/livr> in
590 JavaScript, and with the
591 L<implementations|https://livr-spec.org/introduction/implementations.html> for
592 PHP, Python, Go, Java, Ruby, Erlang, Lua, Raku and Swift. You can try rules in
593 the L<playground|https://livr-spec.org/playground.html>.
594  
595 =head2 Adding your own rules
596  
597 The simplest way is an alias: a new name for a combination of rules, with its
598 own error code. Aliases are a part of the specification, so other
599 implementations understand them too.
600  
601 Validator::LIVR->register_aliased_default_rule({
602 name => 'adult_age',
603 rules => [ 'positive_integer', { min_number => 18 } ],
604 error => 'WRONG_AGE',
605 });
606  
607 my $validator = Validator::LIVR->new({ age => [ 'required', 'adult_age' ] });
608  
609 For anything else, write the rule in Perl, see L</WRITING RULES IN PERL>.
610  
611 =head1 RULES
612  
613 The built-in rules, grouped as in the specification. Each group links to its
614 page in the specification, which has the details and edge cases.
615  
616 A rule that expects a string or a number returns C<FORMAT_ERROR> for a hash or
617 a list. A rule that expects a hash or a list returns C<FORMAT_ERROR> for
618 anything else.
619  
620 =head2 Common rules
621  
622 L<Specification|https://livr-spec.org/validation-rules/common-rules.html>
623  
624 =over 4
625  
626 =item C<required>
627  
628 The field is present and not empty: not C<undef> and not C<''>.
629 Error: C<REQUIRED>.
630  
631 =item C<not_empty>
632  
633 The field can be missing, but when it is there, it is not C<''>.
634 Error: C<CANNOT_BE_EMPTY>.
635  
636 =item C<not_empty_list>
637  
638 The field is a list with at least one item.
639 Errors: C<CANNOT_BE_EMPTY>, C<FORMAT_ERROR>.
640  
641 =item C<any_object>
642  
643 The field is a hash with any content.
644 Error: C<FORMAT_ERROR>.
645  
646 =back
647  
648 =head2 String rules
649  
650 L<Specification|https://livr-spec.org/validation-rules/string-rules.html>
651  
652 =over 4
653  
654 =item C<string>
655  
656 Any string or number.
657 Error: C<FORMAT_ERROR>.
658  
659 =item C<< { eq => $value } >>
660  
661 The value is equal to C<$value>, compared as strings: C<2> equals C<"2">, and
662 a boolean such as C<JSON::PP::true> equals C<"true">. As in Validator::LIVR 2.0,
663 true also equals C<"1"> and false C<"0">. The output is C<$value>.
664 Error: C<NOT_ALLOWED_VALUE>.
665  
666 =item C<< { one_of => [ @values ] } >>
667  
668 The value is equal to one of C<@values>, compared as in C<eq>. As in
669 Validator::LIVR 2.0, a boolean value also equals C<1> or C<"1"> (true) and C<0>
670 or C<"0"> (false). The output is that one of C<@values>.
671 Error: C<NOT_ALLOWED_VALUE>.
672  
673 =item C<< { min_length => $length } >>
674  
675 The value has at least C<$length> characters.
676 Error: C<TOO_SHORT>.
677  
678 =item C<< { max_length => $length } >>
679  
680 The value has at most C<$length> characters.
681 Error: C<TOO_LONG>.
682  
683 =item C<< { length_equal => $length } >>
684  
685 The value has exactly C<$length> characters.
686 Errors: C<TOO_SHORT>, C<TOO_LONG>.
687  
688 =item C<< { length_between => [ $min, $max ] } >>
689  
690 The value has from C<$min> to C<$max> characters.
691 Errors: C<TOO_SHORT>, C<TOO_LONG>.
692  
693 =item C<< { like => $regex } >>, C<< { like => [ $regex, 'i' ] } >>
694  
695 The value matches the regular expression. The C<i> flag makes it case
696 insensitive.
697 Error: C<WRONG_FORMAT>.
698  
699 The rule is experimental in the specification. The syntax of regular
700 expressions differs between languages, so stick to the common features when
701 you share rules.
702  
703 =back
704  
705 =head2 Numeric rules
706  
707 L<Specification|https://livr-spec.org/validation-rules/numeric-rules.html>
708  
709 =over 4
710  
711 =item C<integer>
712  
713 An integer, such as C<-5> or C<42>.
714 Error: C<NOT_INTEGER>.
715  
716 =item C<positive_integer>
717  
718 An integer greater than zero.
719 Error: C<NOT_POSITIVE_INTEGER>.
720  
721 =item C<decimal>
722  
723 A number, such as C<-1.5> or C<42>.
724 Error: C<NOT_DECIMAL>.
725  
726 =item C<positive_decimal>
727  
728 A number greater than zero.
729 Error: C<NOT_POSITIVE_DECIMAL>.
730  
731 =item C<< { min_number => $min } >>
732  
733 A number that is not less than C<$min>.
734 Errors: C<NOT_NUMBER>, C<TOO_LOW>.
735  
736 =item C<< { max_number => $max } >>
737  
738 A number that is not greater than C<$max>.
739 Errors: C<NOT_NUMBER>, C<TOO_HIGH>.
740  
741 =item C<< { number_between => [ $min, $max ] } >>
742  
743 A number from C<$min> to C<$max>.
744 Errors: C<NOT_NUMBER>, C<TOO_LOW>, C<TOO_HIGH>.
745  
746 =back
747  
748 =head2 Special rules
749  
750 L<Specification|https://livr-spec.org/validation-rules/special-rules.html>
751  
752 =over 4
753  
754 =item C<email>
755  
756 An email address, such as C<john.smith@example.com>, without a name, comments
757 or spaces around it. The domain has a TLD or is an IP address in brackets.
758 Error: C<WRONG_EMAIL>.
759  
760 =item C<url>
761  
762 An C<http> or C<https> URL, such as C<https://example.com/path?query#fragment>.
763 The host is a domain name, such as C<example.com> or C<intranet>, or an IPv4
764 address. Domain names in other languages work in decoded strings, not in UTF-8
765 bytes.
766 Error: C<WRONG_URL>.
767  
768 =item C<iso_date>, C<< { iso_date => { min => $date, max => $date } } >>
769  
770 A date as C<YYYY-MM-DD> that exists in the calendar: C<2024-02-29> is valid,
771 C<2025-02-29> is not.
772 Error: C<WRONG_DATE>.
773  
774 LIVR 2.5: the bounds C<min> and C<max>, both optional and inclusive, are dates
775 or C<today>, C<yesterday> and C<tomorrow>: the current date in UTC, from the
776 system time (see L</Testing rules with the current date>). An argument that is
777 not a hash dies; LIVR 2.0 ignored it. A boolean gives C<WRONG_DATE>.
778 Errors: C<WRONG_DATE>, C<DATE_TOO_EARLY>, C<DATE_TOO_LATE>, C<FORMAT_ERROR>.
779  
780 =item C<< { equal_to_field => $field } >>
781  
782 The value is equal to the value of another field, such as a password
783 confirmation.
784 Error: C<FIELDS_NOT_EQUAL>.
785  
786 =back
787  
788 =head2 Metarules
789  
790 L<Specification|https://livr-spec.org/validation-rules/metarules.html>
791  
792 Metarules validate nested data with their own rule sets. Their errors are
793 nested too: a hash of errors for an object, and a list for a list, with
794 C<undef> for the valid items.
795  
796 =over 4
797  
798 =item C<< { nested_object => \%rules } >>
799  
800 A hash validated with C<\%rules>.
801  
802 =item C<< { list_of => \@rules } >>, C<< { list_of => $rule } >>
803  
804 A list, each item validated with the rules.
805  
806 =item C<< { list_of_objects => \%rules } >>
807  
808 A list of hashes, each validated with C<\%rules>.
809  
810 =item C<< { variable_object => [ $selector, { $type => \%rules, ... } ] } >>
811  
812 A hash validated with the rules for the value of its C<$selector> field. The
813 error is C<FORMAT_ERROR> when the hash has no rules for that value.
814  
815 payment => [ 'required', { variable_object => [ type => {
816 card => {
817 type => 'required',
818 card_number => [ 'required', { length_equal => 16 } ],
819 },
820 iban => {
821 type => 'required',
822 iban => 'required',
823 },
824 } ] } ],
825  
826 =item C<< { list_of_different_objects => [ $selector, { $type => \%rules, ... } ] } >>
827  
828 A list of hashes, each validated as in C<variable_object>.
829  
830 =item C<< { or => [ $rules1, $rules2, ... ] } >>
831  
832 The value passes at least one of the rule sets. Each rule set is a rule or a
833 list of rules. When all of them fail, the error is the error of the last one.
834  
835 id => { or => [ 'email', 'positive_integer' ] },
836  
837 =back
838  
839 The rules of C<or> and of aliases see the fields next to the field, so
840 C<equal_to_field> works in them. The items of C<list_of> have no fields next to
841 them.
842  
843 =head2 Modifiers
844  
845 L<Specification|https://livr-spec.org/validation-rules/modifiers.html>
846  
847 Modifiers change the value and never fail.
848  
849 =over 4
850  
851 =item C<trim>
852  
853 Removes the spaces at the start and at the end.
854  
855 =item C<to_lc>
856  
857 Converts to lower case.
858  
859 =item C<to_uc>
860  
861 Converts to upper case.
862  
863 =item C<< { remove => $chars } >>
864  
865 Removes each of the characters in C<$chars>, so C<< { remove => ' -()' } >>
866 turns C<(050) 123-45-67> into C<0501234567>.
867  
868 =item C<< { leave_only => $chars } >>
869  
870 Removes all characters except the ones in C<$chars>.
871  
872 =item C<< { default => $value } >>
873  
874 Sets C<$value> when the field is missing or empty.
875  
876 =back
877  
878 =head2 LIVR 2.5 rules
879  
880 L<LIVR 2.5 specification|https://github.com/koorchik/LIVR/blob/master/drafts/v2.5.md>,
881 L<all rules on the site|https://livr-spec.org/validation-rules.html>
882  
883 The rules added in LIVR 2.5. They are loaded on first use, so they do not
884 slow down C<use Validator::LIVR>. They check their arguments when the validator
885 is built: L</prepare> dies on a wrong argument, such as C<< { boolean => 1 } >>
886 or C<< { digest => 'MD5' } >>, or on C<undef> or an empty list in place of
887 rules in C<when>, C<values> and C<keys> (use C<any> for no rules), and on
888 C<undef> or a list in their lists of rules, such as C<< [ 'required', [] ] >>.
889 Arguments after the ones a rule takes are ignored, and a number and a string
890 with that number are the same argument. C<undef> is an argument too, and no LIVR 2.5 rule takes it:
891 C<< { boolean => undef } >> dies, like C<< { boolean => [undef] } >>. The LIVR 2.0
892 rules and custom rules get C<undef> as an argument, as before, and
893 C<< { iso_date => undef } >> stays C<iso_date>, as LIVR 2.0 ignored its arguments.
894  
895 They compare and check the string form of a value: a boolean, such as
896 C<JSON::PP::true>, is C<true> or C<false>. Format and checksum rules return
897 their own error code for a boolean, and C<FORMAT_ERROR> for a hash or a list.
898  
899 =over 4
900  
901 =item C<boolean>
902  
903 C<true>, C<false>, C<1>, C<0>, C<"1">, C<"0">, C<"true"> or C<"false">. The
904 output is C<JSON::PP::true> or C<JSON::PP::false>.
905 Errors: C<NOT_BOOLEAN>, C<FORMAT_ERROR>.
906  
907 =item C<< { not_one_of => [ @values ] } >>
908  
909 The value is none of C<@values>.
910 Errors: C<NOT_ALLOWED_VALUE>, C<FORMAT_ERROR>.
911  
912 =item C<< { max_decimals => $count } >>
913  
914 A number with at most C<$count> digits after the decimal point; trailing zeros
915 do not count. The output is a number.
916 Errors: C<TOO_MANY_DECIMALS>, C<NOT_NUMBER>, C<FORMAT_ERROR>.
917  
918 =item C<digits>
919  
920 ASCII digits, the leading zeros are kept: the output is a string.
921 Errors: C<NOT_DIGITS>, C<FORMAT_ERROR>.
922  
923 =item C<< { starts_with => [ @strings ] } >>, C<< { ends_with => [ @strings ] } >>, C<< { contains => [ @strings ] } >>
924  
925 The value starts with, ends with or contains one of C<@strings>.
926 Errors: C<WRONG_FORMAT>, C<FORMAT_ERROR>.
927  
928 =item C<iso_datetime>, C<< { iso_datetime => { min => $bound, max => $bound } } >>
929  
930 A date and a time with an offset, such as C<2026-10-29T10:00+02:00>. The output
931 is the time in UTC, C<2026-10-29T08:00:00.000Z>. A bound is a datetime, a date
932 (its start as C<min>, its end as C<max>) or C<today>, C<yesterday> and
933 C<tomorrow>.
934 Errors: C<WRONG_DATETIME>, C<DATETIME_TOO_EARLY>, C<DATETIME_TOO_LATE>, C<FORMAT_ERROR>.
935  
936 =item C<iso_time>, C<< { iso_time => { min => $time, max => $time } } >>
937  
938 C<HH:MM>, C<HH:MM:SS> or C<HH:MM:SS.fraction>. With C<min> greater than C<max>
939 the range goes over midnight.
940 Errors: C<WRONG_TIME>, C<TIME_TOO_EARLY>, C<TIME_TOO_LATE>, C<FORMAT_ERROR>.
941  
942 =item C<< { required_if => { $reference => $value, ... } } >>
943  
944 The field is required when all referenced fields have the given values, or one
945 of the values of a list. A reference is a field name or a path, such as
946 C<address/country>.
947 Error: C<REQUIRED>.
948  
949 =item C<< { when => [ $reference, $condition, $rules_if_true, $rules_if_false ] } >>, C<< { when => [ $reference, { $value => $rules, ... } ] } >>
950  
951 Validates the field with rules that depend on another field: on whether it
952 passes the C<$condition> rules, or on its value.
953  
954 vat_number => { when => [ 'type', { eq => 'company' }, [ 'required', 'string' ], { eq => '' } ] },
955  
956 Errors: C<NOT_ALLOWED_VALUE> and the errors of the rules.
957  
958 =item C<< { values => \@rules } >>, C<< { keys => \@rules } >>
959  
960 A hash with every value or every key validated with the rules. A wrong key gets
961 C<WRONG_KEY>.
962 Errors: C<WRONG_KEY>, C<FORMAT_ERROR> and the errors of the rules.
963  
964 =item C<any>
965  
966 Any value, the hashes and lists too, stays in the output unchanged.
967  
968 =item C<< { list_length => $length } >>, C<< { list_length => [ $min, $max ] } >>, C<< { list_length => { min => $min, max => $max } } >>
969  
970 A list with that number of items.
971 Errors: C<TOO_FEW_ITEMS>, C<TOO_MANY_ITEMS>, C<FORMAT_ERROR>.
972  
973 =item C<unique>, C<< { unique => [ @keys ] } >>
974  
975 A list without duplicates, or of hashes without duplicate values of C<@keys>.
976 Errors: C<NOT_UNIQUE_ITEMS>, C<FORMAT_ERROR>.
977  
978 =item C<< { split => $separator } >>
979  
980 A modifier: splits a string into a list, C<"1,2,3"> into C<["1", "2", "3"]>.
981 A number or a boolean is split in its string form, a list stays as it is.
982  
983 =item Formats
984  
985 C<uuid> (or C<< { uuid => [ 'v4', 'v7' ] } >>), C<ip> (or C<< { ip => 'v4' } >>,
986 C<< { ip => 'v6' } >>), C<cidr> (the same), C<hostname>, C<base64> (or
987 C<< { base64 => 'url' } >>), C<hex>, C<< { digest => [ 'md5', 'sha256' ] } >>
988 (also C<sha1>, C<sha384>, C<sha512>), C<mongo_id>, C<hex_color>, C<mac> (or
989 C<< { mac => 64 } >>), C<e164>, C<semver> and C<jwt>.
990 Errors: C<WRONG_UUID>, C<WRONG_IP>, C<WRONG_CIDR>, C<WRONG_HOSTNAME>,
991 C<WRONG_BASE64>, C<WRONG_HEX>, C<WRONG_DIGEST>, C<WRONG_MONGO_ID>,
992 C<WRONG_HEX_COLOR>, C<WRONG_MAC>, C<WRONG_E164>, C<WRONG_SEMVER>, C<WRONG_JWT>,
993 C<FORMAT_ERROR>.
994  
995 =item Checksums
996  
997 C<luhn>, C<credit_card> and C<iban>. The value is checked as it is: remove
998 spaces before, with C<< { remove => ' -' } >>.
999 Errors: C<WRONG_CHECKSUM>, C<WRONG_CREDIT_CARD_NUMBER>, C<WRONG_IBAN>, C<FORMAT_ERROR>.
1000  
1001 =back
1002  
1003 =head2 Testing rules with the current date
1004  
1005 The bounds C<today>, C<yesterday> and C<tomorrow> read the system time with
1006 C<time>. To fix it in tests, load L<Test::MockTime> before the first validator
1007 with such a bound is built:
1008  
1009 use Test::MockTime qw(set_fixed_time);
1010 use Validator::LIVR;
1011  
1012 set_fixed_time('2026-10-18T12:00:00Z', '%Y-%m-%dT%H:%M:%SZ');
1013  
1014 =head1 CLASS METHODS
1015  
1016 =head2 new
1017  
1018 my $validator = Validator::LIVR->new( \%rules );
1019 my $validator = Validator::LIVR->new( \%rules, $is_auto_trim );
1020  
1021 Creates a validator. With a true C<$is_auto_trim>, it trims all strings of the
1022 input, the nested ones too, before validation, so the output is trimmed as
1023 well. When C<$is_auto_trim> is C<undef>, the value set with
1024 L</default_auto_trim> is used.
1025  
1026 =head2 register_default_rules
1027  
1028 Validator::LIVR->register_default_rules(
1029 my_rule => \&my_rule_builder,
1030 other_rule => \&other_rule_builder,
1031 );
1032  
1033 Adds rules or replaces existing ones for all validators created after the call.
1034 See L</WRITING RULES IN PERL> for how to write a rule builder.
1035  
1036 =head2 register_aliased_default_rule
1037  
1038 Validator::LIVR->register_aliased_default_rule({
1039 name => 'valid_address',
1040 rules => { nested_object => {
1041 country => 'required',
1042 city => 'required',
1043 zip => 'positive_integer',
1044 } },
1045 error => 'WRONG_ADDRESS', # optional
1046 });
1047  
1048 Adds an alias for all validators created after the call. Then the alias works
1049 as any other rule:
1050  
1051 { address => [ 'required', 'valid_address' ] }
1052  
1053 Without C<error>, the alias returns the error of its rules.
1054  
1055 =head2 get_default_rules
1056  
1057 my $rule_builders = Validator::LIVR->get_default_rules();
1058  
1059 Returns a hashref that maps rule names to the rule builders that new validators
1060 get.
1061  
1062 =head2 default_auto_trim
1063  
1064 Validator::LIVR->default_auto_trim(1);
1065  
1066 Turns auto trim on or off for validators created after the call. See L</new>.
1067  
1068 =head1 OBJECT METHODS
1069  
1070 =head2 validate
1071  
1072 my $valid_data = $validator->validate( \%input );
1073  
1074 Returns a hashref with the valid data: only the fields that have rules, with
1075 the changes made by modifiers. On errors returns C<undef>, and L</get_errors>
1076 returns the errors.
1077  
1078 =head2 get_errors
1079  
1080 my $errors = $validator->get_errors();
1081  
1082 Returns the errors of the last L</validate> call, or C<undef> when it passed.
1083 The errors are a hashref that maps fields to error codes, with nested errors for
1084 metarules:
1085  
1086 {
1087 email => 'WRONG_EMAIL',
1088 address => { zip => 'NOT_POSITIVE_INTEGER' },
1089 products => [ undef, { quantity => 'TOO_LOW' } ],
1090 }
1091  
1092 When the input is not a hashref, the errors are the string C<FORMAT_ERROR>.
1093  
1094 =head2 register_rules
1095  
1096 $validator->register_rules( my_rule => \&my_rule_builder, ... );
1097  
1098 Adds rules or replaces existing ones, as L</register_default_rules> does, for
1099 this validator only. Returns the validator, so the call can be chained.
1100  
1101 =head2 register_aliased_rule
1102  
1103 $validator->register_aliased_rule({
1104 name => 'strong_password',
1105 rules => { min_length => 12 },
1106 error => 'WEAK_PASSWORD',
1107 });
1108  
1109 Adds an alias, as L</register_aliased_default_rule> does, for this validator
1110 only. Returns the validator.
1111  
1112 =head2 get_rules
1113  
1114 my $rule_builders = $validator->get_rules();
1115  
1116 Returns a hashref that maps rule names to the rule builders of this validator.
1117  
1118 =head2 prepare
1119  
1120 my $validator = Validator::LIVR->new($rules)->prepare();
1121  
1122 Builds the validators of all rules and returns the validator. L</validate> does
1123 it on the first call, so you need C<prepare> only to find mistakes early. It
1124 dies with C<Rule [name] not registered> when a rule is unknown, and with
1125 C<Rule [name1, name2] should have one name> when a hash has several rules.
1126 Register your rules before C<prepare> or the first L</validate>.
1127  
1128 =head1 WRITING RULES IN PERL
1129  
1130 A rule is a builder: a sub that gets the arguments of the rule and returns a
1131 validator sub. The builder is called once, when the validator is prepared. The
1132 validator sub is called for every value.
1133  
1134 Here is how C<max_number> could be written:
1135  
1136 use Scalar::Util qw(looks_like_number);
1137  
1138 Validator::LIVR->register_default_rules( max_number => sub {
1139 my ( $max_number, $rule_builders ) = @_;
1140  
1141 return sub {
1142 my ( $value, $all_values, $output_ref ) = @_;
1143  
1144 # Empty values are the job of "required"
1145 return if !defined($value) || $value eq '';
1146  
1147 return 'FORMAT_ERROR' if ref($value);
1148 return 'NOT_NUMBER' if !looks_like_number($value);
1149 return 'TOO_HIGH' if $value > $max_number;
1150 return;
1151 };
1152 });
1153  
1154 The builder gets the arguments of the rule, then a hashref of all rule builders
1155 of the validator, which the builder must not change:
1156  
1157 'my_rule' # ( $rule_builders )
1158 { my_rule => $arg } # ( $arg, $rule_builders )
1159 { my_rule => [ $arg ] } # ( $arg, $rule_builders )
1160 { my_rule => [ $arg1, $arg2 ] } # ( $arg1, $arg2, $rule_builders )
1161  
1162 The validator sub gets:
1163  
1164 =over 4
1165  
1166 =item C<$value>
1167  
1168 The value of the field, as the previous rules of the field left it.
1169  
1170 =item C<$all_values>
1171  
1172 The hash that has the field, to compare it with other fields, as
1173 C<equal_to_field> does. Inside C<or> and aliases, it is the hash of the field
1174 that uses them. Inside C<list_of>, C<values> and C<keys>, it is empty.
1175  
1176 =item C<$output_ref>
1177  
1178 A reference to the output value. Assign to it to change the value, as
1179 modifiers do.
1180  
1181 =back
1182  
1183 It returns nothing when the value is valid, and an error code when it is not.
1184  
1185 A modifier sets the output and returns nothing:
1186  
1187 Validator::LIVR->register_default_rules( to_ucfirst => sub {
1188 return sub {
1189 my ( $value, undef, $output_ref ) = @_;
1190 return if !defined($value) || ref($value) || $value eq '';
1191  
1192 $$output_ref = ucfirst($value);
1193 return;
1194 };
1195 });
1196  
1197 With C<$rule_builders>, a rule can validate nested data with the same rules,
1198 as metarules do:
1199  
1200 my $validator = Validator::LIVR->new($rules)->register_rules(%$rule_builders)->prepare();
1201  
1202 The built-in rules are short and make good examples:
1203 L<Validator::LIVR::Rules::Common>, L<Validator::LIVR::Rules::String>,
1204 L<Validator::LIVR::Rules::Numeric>, L<Validator::LIVR::Rules::Special>,
1205 L<Validator::LIVR::Rules::Meta> and L<Validator::LIVR::Rules::Modifiers>. The
1206 LIVR 2.5 rules are in L<Validator::LIVR::Rules::Types>,
1207 L<Validator::LIVR::Rules::DateTime>, L<Validator::LIVR::Rules::Conditional>,
1208 L<Validator::LIVR::Rules::Collection> and L<Validator::LIVR::Rules::Format>.
1209  
1210 =head1 SEE ALSO
1211  
1212 =over 4
1213  
1214 =item * L<The LIVR specification|https://livr-spec.org>, with all rules,
1215 L<aliases|https://livr-spec.org/rules-aliasing.html> and a
1216 L<playground|https://livr-spec.org/playground.html>.
1217  
1218 =item * L<The LIVR repository|https://github.com/koorchik/LIVR>, with the
1219 specification and its test suite.
1220  
1221 =item * L<LIVR implementations|https://livr-spec.org/introduction/implementations.html>
1222 in other languages.
1223  
1224 =back
1225  
1226 =head1 BUGS AND SUPPORT
1227  
1228 Please report bugs and ideas in
1229 L<GitHub Issues|https://github.com/koorchik/Validator-LIVR/issues>. The source
1230 is at L<https://github.com/koorchik/Validator-LIVR>.
1231  
1232 You can read this documentation with C<perldoc Validator::LIVR>, or on
1233 L<MetaCPAN|https://metacpan.org/pod/Validator::LIVR>.
1234  
1235 =head1 AUTHOR
1236  
1237 Viktor Turskyi, C<< <koorchik at cpan.org> >>
1238  
1239 =head1 LICENSE AND COPYRIGHT
1240  
1241 Copyright 2012-2026 Viktor Turskyi.
1242  
1243 This program is free software; you can redistribute it and/or modify it
1244 under the terms of the Artistic License (2.0). You may obtain a
1245 copy of the full license at:
1246  
1247 L<https://www.perlfoundation.org/artistic-license-20.html>
1248  
1249 Any use, modification, and distribution of the Standard or Modified
1250 Versions is governed by this Artistic License. By using, modifying or
1251 distributing the Package, you accept this license. Do not use, modify,
1252 or distribute the Package, if you do not accept this license.
1253  
1254 If your Modified Version has been derived from a Modified Version made
1255 by someone other than you, you are nevertheless required to ensure that
1256 your Modified Version complies with the requirements of this license.
1257  
1258 This license does not grant you the right to use any trademark, service
1259 mark, tradename, or logo of the Copyright Holder.
1260  
1261 This license includes the non-exclusive, worldwide, free-of-charge
1262 patent license to make, have made, use, offer to sell, sell, import and
1263 otherwise transfer the Package with respect to any patent claims
1264 licensable by the Copyright Holder that are necessarily infringed by the
1265 Package. If you institute patent litigation (including a cross-claim or
1266 counterclaim) against any party alleging that the Package constitutes
1267 direct or contributory patent infringement, then this Artistic License
1268 to you shall terminate on the date that such litigation is filed.
1269  
1270 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
1271 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
1272 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
1273 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
1274 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
1275 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
1276 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
1277 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1278  
1279 =cut
« LIVR/Rules/Meta.pm ↑ Summary LIVR/Rules/Format.pm »