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.2';
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 1096 ▶sub new {
Subroutine new: called CC=2 SCAR=7.0
Pod documented
125 1096 my ($class, $livr_rules, $is_auto_trim) = @_;
126  
127 1096 ▶ my $self = bless {
Condition66%2/3
$is_auto_trim // $IS_DEFAULT_AUTO_TRIM
l!l&&r!l&&!r
2710690
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 1096 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 1098 ▶sub prepare {
Subroutine prepare: called CC=4 SCAR=13.9
Pod documented
174 1098 my $self = shift;
175  
176 1098 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 1098 my $rule_builders = $self->{validator_builders};
181 1098 $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 1098 foreach my $field ( keys %$all_rules ) {
186 3752 my $field_rules = $all_rules->{$field};
187 3752 ▶ $field_rules = [$field_rules] if ref($field_rules) ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $field_rules ne "ARRAY" 3098 654 3752
188  
189 3752 my @validators;
190 3752 foreach my $rule (@$field_rules) {
191 4197 my ($name, $args) = $self->_parse_rule($rule);
192 4192 push @validators, $self->_build_validator($name, $args, $rule_builders);
193 }
194 3519 $self->{validators}{$field} = \@validators;
195 }
196  
197 865 $self->{is_prepared} = 1;
198  
199 865 return $self;
200 }
201  
202 446 ▶sub validate {
Subroutine validate: called CC=16 SCAR=27.7
Pod documented
203 446 my ($self, $data) = @_;
204 446 ▶ $self->prepare() unless $self->{is_prepared};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"is_prepared"} 217 229 446
205  
206 442 ▶ if ( ref($data) ne 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data ne "HASH") 1 441 442
207 1 $self->{errors} = 'FORMAT_ERROR';
208 1 return;
209 }
210  
211 441 ▶ $data = $self->_auto_trim($data) if $self->{is_auto_trim};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"is_auto_trim"} 2 439 441
212  
213 441 my ( %errors, %result );
214 441 my $all_validators = $self->{validators};
215  
216 441 foreach my $field_name ( keys %$all_validators ) {
217 2848 my $validators = $all_validators->{$field_name};
218 2848 ▶ next unless $validators && @$validators;
Branch: 1 branch
BranchTrueFalseTotal
unless $validators and @$validators 0 2848 2848
Condition33%1/3
$validators and @$validators
!ll&&!rl&&r
002848
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 2848 my $value = $data->{$field_name};
221  
222 # The output of the previous rules, the same as $result{$field_name}
223 2848 my ( $has_output, $output );
224  
225 2848 foreach my $v_cb (@$validators) {
226 3039 ▶ my $field_result = $output // $value;
Condition100%3/3
$output // $value
l!l&&r!l&&!r
1812578280
MC/DC100%2/2
$output // $value
$output $value
Truth table100%3/3
A // B
A= $outputB= $value
ABresult
1X1
011
000
227  
228 3039 ▶ my $err_code = $v_cb->( $has_output ? $output : $value, $data, \$field_result );
Branch: 1 branch
BranchTrueFalseTotal
$has_output ? : 186 2853 3039
229  
230 3039 ▶ if ( $err_code ) {
Branch: 3 branches
BranchTrueFalseTotal
if ($err_code) { } 1366 1673 3039
elsif (defined $field_result) { } 1476 197 1673
elsif (not $has_output and exists $data->{$field_name}) { } 79 120 199
231 1366 $errors{$field_name} = $err_code;
232 1366 $has_output = 0;
233 1366 last;
234 } elsif ( defined($field_result) ) {
235 1476 ( $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 2848 ▶ $result{$field_name} = $output if $has_output;
Branch: 1 branch
BranchTrueFalseTotal
if $has_output 1371 1477 2848
242 }
243  
244 441 ▶ if ( keys %errors ) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %errors) { } 197 244 441
245 197 $self->{errors} = \%errors;
246 197 return;
247 } else {
248 244 $self->{errors} = undef;
249 244 return \%result;
250 }
251 }
252  
253 389 ▶sub get_errors {
Subroutine get_errors: called CC=1 SCAR=0.0
Pod documented
254 389 my $self = shift;
255 389 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 4197 ▶sub _parse_rule {
Subroutine _parse_rule: called CC=4 SCAR=13.9
349 4197 my ($self, $livr_rule) = @_;
350  
351 4197 my ($name, $args);
352  
353 4197 ▶ if ( ref($livr_rule) eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $livr_rule eq 'HASH') { } 1996 2201 4197
354 # Only the first key would be used, and the order of keys is random
355 1996 my @names = sort keys %$livr_rule;
356 1996 ▶ die 'Rule [' . join( ', ', @names ) . "] should have one name\n" if @names != 1;
Branch: 1 branch
BranchTrueFalseTotal
if @names != 1 5 1991 1996
357  
358 1991 $name = $names[0];
359 1991 $args = $livr_rule->{$name};
360 1991 ▶ $args = [$args] unless ref($args) eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "ARRAY" 1289 702 1991
361 } else {
362 2201 $name = $livr_rule;
363 2201 $args = [];
364 }
365  
366 4192 return ($name, $args);
367 }
368  
369 4192 ▶sub _build_validator {
Subroutine _build_validator: called CC=3 SCAR=11.2
370 4192 my ($self, $name, $args, $rule_builders) = @_;
371 4192 ▶ $rule_builders //= $self->{validator_builders};
Condition33%1/3
$rule_builders //= $self->{"validator_builders"}
l!l&&r!l&&!r
419200
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 4192 my $rule_builder = $rule_builders->{$name};
374 4192 ▶ die "Rule [$name] not registered\n" unless $rule_builder;
Branch: 1 branch
BranchTrueFalseTotal
unless $rule_builder 12 4180 4192
375  
376 4180 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 passes the
476 test suite of the specification. It also has the rules of the LIVR 2.5 draft,
477 see L</LIVR 2.5 rules>, and passes its test suite.
478  
479 =over 4
480  
481 =item * B<Declarative rules> that you can keep in JSON and share with other services.
482  
483 =item * B<All errors at once>, not just the first one.
484  
485 =item * B<Only described fields in the output.> A field without rules, such as an
486 unexpected C<is_admin>, never reaches your code.
487  
488 =item * B<Nested data>: objects, lists, lists of objects and objects of several types.
489  
490 =item * B<Error codes, not messages>, such as C<REQUIRED> or C<TOO_SHORT>. Turn them
491 into messages in any language you need.
492  
493 =item * B<Data cleanup> with modifiers, such as C<trim>, C<to_lc> and C<default>.
494  
495 =item * B<Your own rules>, as aliases of existing rules or as Perl code.
496  
497 =item * B<No dependencies>: only modules that come with Perl.
498  
499 =back
500  
501 Use it for user input, configs, API requests and responses, or any other data
502 that has to have a known shape.
503  
504 =head1 A QUICK TOUR
505  
506 =head2 Writing rules
507  
508 A rule set maps each field to its rules. A rule is written in one of these
509 ways:
510  
511 {
512 name => 'required', # a rule without arguments
513 bio => { max_length => 1000 }, # a rule with one argument
514 nick => { length_between => [ 3, 20 ] }, # a rule with several arguments
515 email => [ 'required', 'email' ], # several rules
516 }
517  
518 Several rules of a field are applied in order, and the field stops at its
519 first error. A hash is always one rule, so two rules with arguments are two
520 hashes: C<< [ { min_length => 3 }, { max_length => 20 } ] >>.
521  
522 Most rules accept empty values: C<undef> and the empty string. So a field is
523 optional until you add C<required>:
524  
525 {
526 age => 'positive_integer', # can be missing
527 id => [ 'required', 'positive_integer' ], # must be present
528 }
529  
530 =head2 Validating nested data
531  
532 Metarules describe the structure of the data, and errors have the same shape
533 as the data:
534  
535 my $validator = Validator::LIVR->new({
536 order_id => [ 'required', 'positive_integer' ],
537 address => [ 'required', { nested_object => {
538 country => [ 'required', { one_of => [ 'Ukraine', 'USA' ] } ],
539 city => 'required',
540 zip => 'positive_integer',
541 } } ],
542 products => [ 'required', 'not_empty_list', { list_of_objects => {
543 product_id => [ 'required', 'positive_integer' ],
544 quantity => [ 'required', { min_number => 1 } ],
545 } } ],
546 tags => { list_of => [ 'string', { max_length => 10 } ] },
547 });
548  
549 For an order with an unknown country, a second product with a quantity of 0
550 and a second tag that is too long, C<get_errors> returns:
551  
552 {
553 address => { country => 'NOT_ALLOWED_VALUE' },
554 products => [ undef, { quantity => 'TOO_LOW' } ],
555 tags => [ undef, 'TOO_LONG' ],
556 }
557  
558 =head2 Cleaning data
559  
560 Modifiers change the value for the next rules and for the output:
561  
562 my $validator = Validator::LIVR->new({
563 email => [ 'trim', 'required', 'email', 'to_lc' ],
564 phone => { leave_only => '0123456789' },
565 role => [ { default => 'user' }, { one_of => [ 'user', 'admin' ] } ],
566 });
567  
568 $validator->validate({ email => ' John@Example.COM ', phone => '+38 (050) 123-45-67' });
569 # { email => 'john@example.com', phone => '380501234567', role => 'user' }
570  
571 To trim every string of the input before validation, turn on auto trim for
572 one validator with C<< Validator::LIVR->new( $rules, 1 ) >>, or for all new
573 validators with C<< Validator::LIVR->default_auto_trim(1) >>.
574  
575 =head2 Sharing rules with other languages
576  
577 Rules are plain data, so they can live in a JSON file:
578  
579 {
580 "email": [ "required", "email" ],
581 "password": [ "required", { "min_length": 10 } ]
582 }
583  
584 use JSON::PP qw(decode_json);
585  
586 my $validator = Validator::LIVR->new( decode_json($json_rules) );
587  
588 The same file works with L<livr|https://www.npmjs.com/package/livr> in
589 JavaScript, and with the
590 L<implementations|https://livr-spec.org/introduction/implementations.html> for
591 PHP, Python, Go, Java, Ruby, Erlang, Lua, Raku and Swift. You can try rules in
592 the L<playground|https://livr-spec.org/playground.html>.
593  
594 =head2 Adding your own rules
595  
596 The simplest way is an alias: a new name for a combination of rules, with its
597 own error code. Aliases are a part of the specification, so other
598 implementations understand them too.
599  
600 Validator::LIVR->register_aliased_default_rule({
601 name => 'adult_age',
602 rules => [ 'positive_integer', { min_number => 18 } ],
603 error => 'WRONG_AGE',
604 });
605  
606 my $validator = Validator::LIVR->new({ age => [ 'required', 'adult_age' ] });
607  
608 For anything else, write the rule in Perl, see L</WRITING RULES IN PERL>.
609  
610 =head1 RULES
611  
612 The built-in rules, grouped as in the specification. Each group links to its
613 page in the specification, which has the details and edge cases.
614  
615 A rule that expects a string or a number returns C<FORMAT_ERROR> for a hash or
616 a list. A rule that expects a hash or a list returns C<FORMAT_ERROR> for
617 anything else.
618  
619 =head2 Common rules
620  
621 L<Specification|https://livr-spec.org/validation-rules/common-rules.html>
622  
623 =over 4
624  
625 =item C<required>
626  
627 The field is present and not empty: not C<undef> and not C<''>.
628 Error: C<REQUIRED>.
629  
630 =item C<not_empty>
631  
632 The field can be missing, but when it is there, it is not C<''>.
633 Error: C<CANNOT_BE_EMPTY>.
634  
635 =item C<not_empty_list>
636  
637 The field is a list with at least one item.
638 Errors: C<CANNOT_BE_EMPTY>, C<FORMAT_ERROR>.
639  
640 =item C<any_object>
641  
642 The field is a hash with any content.
643 Error: C<FORMAT_ERROR>.
644  
645 =back
646  
647 =head2 String rules
648  
649 L<Specification|https://livr-spec.org/validation-rules/string-rules.html>
650  
651 =over 4
652  
653 =item C<string>
654  
655 Any string or number.
656 Error: C<FORMAT_ERROR>.
657  
658 =item C<< { eq => $value } >>
659  
660 The value is equal to C<$value>, compared as strings: C<2> equals C<"2">, and
661 a boolean such as C<JSON::PP::true> equals C<"true">. As in Validator::LIVR 2.0,
662 true also equals C<"1"> and false C<"0">. The output is C<$value>.
663 Error: C<NOT_ALLOWED_VALUE>.
664  
665 =item C<< { one_of => [ @values ] } >>
666  
667 The value is equal to one of C<@values>, compared as in C<eq>. As in
668 Validator::LIVR 2.0, a boolean value also equals C<1> or C<"1"> (true) and C<0>
669 or C<"0"> (false). The output is that one of C<@values>.
670 Error: C<NOT_ALLOWED_VALUE>.
671  
672 =item C<< { min_length => $length } >>
673  
674 The value has at least C<$length> characters.
675 Error: C<TOO_SHORT>.
676  
677 =item C<< { max_length => $length } >>
678  
679 The value has at most C<$length> characters.
680 Error: C<TOO_LONG>.
681  
682 =item C<< { length_equal => $length } >>
683  
684 The value has exactly C<$length> characters.
685 Errors: C<TOO_SHORT>, C<TOO_LONG>.
686  
687 =item C<< { length_between => [ $min, $max ] } >>
688  
689 The value has from C<$min> to C<$max> characters.
690 Errors: C<TOO_SHORT>, C<TOO_LONG>.
691  
692 =item C<< { like => $regex } >>, C<< { like => [ $regex, 'i' ] } >>
693  
694 The value matches the regular expression. The C<i> flag makes it case
695 insensitive.
696 Error: C<WRONG_FORMAT>.
697  
698 The rule is experimental in the specification. The syntax of regular
699 expressions differs between languages, so stick to the common features when
700 you share rules.
701  
702 =back
703  
704 =head2 Numeric rules
705  
706 L<Specification|https://livr-spec.org/validation-rules/numeric-rules.html>
707  
708 =over 4
709  
710 =item C<integer>
711  
712 An integer, such as C<-5> or C<42>.
713 Error: C<NOT_INTEGER>.
714  
715 =item C<positive_integer>
716  
717 An integer greater than zero.
718 Error: C<NOT_POSITIVE_INTEGER>.
719  
720 =item C<decimal>
721  
722 A number, such as C<-1.5> or C<42>.
723 Error: C<NOT_DECIMAL>.
724  
725 =item C<positive_decimal>
726  
727 A number greater than zero.
728 Error: C<NOT_POSITIVE_DECIMAL>.
729  
730 =item C<< { min_number => $min } >>
731  
732 A number that is not less than C<$min>.
733 Errors: C<NOT_NUMBER>, C<TOO_LOW>.
734  
735 =item C<< { max_number => $max } >>
736  
737 A number that is not greater than C<$max>.
738 Errors: C<NOT_NUMBER>, C<TOO_HIGH>.
739  
740 =item C<< { number_between => [ $min, $max ] } >>
741  
742 A number from C<$min> to C<$max>.
743 Errors: C<NOT_NUMBER>, C<TOO_LOW>, C<TOO_HIGH>.
744  
745 =back
746  
747 =head2 Special rules
748  
749 L<Specification|https://livr-spec.org/validation-rules/special-rules.html>
750  
751 =over 4
752  
753 =item C<email>
754  
755 An email address, such as C<john.smith@example.com>, without a name, comments
756 or spaces around it. The domain has a TLD or is an IP address in brackets.
757 Error: C<WRONG_EMAIL>.
758  
759 =item C<url>
760  
761 An C<http> or C<https> URL, such as C<https://example.com/path?query#fragment>.
762 The host is a domain name, such as C<example.com> or C<intranet>, or an IPv4
763 address. Domain names in other languages work in decoded strings, not in UTF-8
764 bytes.
765 Error: C<WRONG_URL>.
766  
767 =item C<iso_date>, C<< { iso_date => { min => $date, max => $date } } >>
768  
769 A date as C<YYYY-MM-DD> that exists in the calendar: C<2024-02-29> is valid,
770 C<2025-02-29> is not.
771 Error: C<WRONG_DATE>.
772  
773 LIVR 2.5: the bounds C<min> and C<max>, both optional and inclusive, are dates
774 or C<today>, C<yesterday> and C<tomorrow>: the current date in UTC, from the
775 system time (see L</Testing rules with the current date>). An argument that is
776 not a hash dies; LIVR 2.0 ignored it. A boolean gives C<WRONG_DATE>.
777 Errors: C<WRONG_DATE>, C<DATE_TOO_EARLY>, C<DATE_TOO_LATE>, C<FORMAT_ERROR>.
778  
779 =item C<< { equal_to_field => $field } >>
780  
781 The value is equal to the value of another field, such as a password
782 confirmation.
783 Error: C<FIELDS_NOT_EQUAL>.
784  
785 =back
786  
787 =head2 Metarules
788  
789 L<Specification|https://livr-spec.org/validation-rules/metarules.html>
790  
791 Metarules validate nested data with their own rule sets. Their errors are
792 nested too: a hash of errors for an object, and a list for a list, with
793 C<undef> for the valid items.
794  
795 =over 4
796  
797 =item C<< { nested_object => \%rules } >>
798  
799 A hash validated with C<\%rules>.
800  
801 =item C<< { list_of => \@rules } >>, C<< { list_of => $rule } >>
802  
803 A list, each item validated with the rules.
804  
805 =item C<< { list_of_objects => \%rules } >>
806  
807 A list of hashes, each validated with C<\%rules>.
808  
809 =item C<< { variable_object => [ $selector, { $type => \%rules, ... } ] } >>
810  
811 A hash validated with the rules for the value of its C<$selector> field. The
812 error is C<FORMAT_ERROR> when the hash has no rules for that value.
813  
814 payment => [ 'required', { variable_object => [ type => {
815 card => {
816 type => 'required',
817 card_number => [ 'required', { length_equal => 16 } ],
818 },
819 iban => {
820 type => 'required',
821 iban => 'required',
822 },
823 } ] } ],
824  
825 =item C<< { list_of_different_objects => [ $selector, { $type => \%rules, ... } ] } >>
826  
827 A list of hashes, each validated as in C<variable_object>.
828  
829 =item C<< { or => [ $rules1, $rules2, ... ] } >>
830  
831 The value passes at least one of the rule sets. Each rule set is a rule or a
832 list of rules. When all of them fail, the error is the error of the last one.
833  
834 id => { or => [ 'email', 'positive_integer' ] },
835  
836 =back
837  
838 The rules of C<or> and of aliases see the fields next to the field, so
839 C<equal_to_field> works in them. The items of C<list_of> have no fields next to
840 them.
841  
842 =head2 Modifiers
843  
844 L<Specification|https://livr-spec.org/validation-rules/modifiers.html>
845  
846 Modifiers change the value and never fail.
847  
848 =over 4
849  
850 =item C<trim>
851  
852 Removes the spaces at the start and at the end.
853  
854 =item C<to_lc>
855  
856 Converts to lower case.
857  
858 =item C<to_uc>
859  
860 Converts to upper case.
861  
862 =item C<< { remove => $chars } >>
863  
864 Removes each of the characters in C<$chars>, so C<< { remove => ' -()' } >>
865 turns C<(050) 123-45-67> into C<0501234567>.
866  
867 =item C<< { leave_only => $chars } >>
868  
869 Removes all characters except the ones in C<$chars>.
870  
871 =item C<< { default => $value } >>
872  
873 Sets C<$value> when the field is missing or empty.
874  
875 =back
876  
877 =head2 LIVR 2.5 rules
878  
879 L<Draft specification|https://github.com/koorchik/LIVR/blob/master/drafts/v2.5.md>
880  
881 The rules of the LIVR 2.5 draft. They are loaded on first use, so they do not
882 slow down C<use Validator::LIVR>. They check their arguments when the validator
883 is built: L</prepare> dies on a wrong argument, such as C<< { boolean => 1 } >>
884 or C<< { digest => 'MD5' } >>, or on C<undef> or an empty list in place of
885 rules in C<when>, C<values> and C<keys> (use C<any> for no rules), and on
886 C<undef> or a list in their lists of rules, such as C<< [ 'required', [] ] >>.
887 Arguments after the ones a rule takes are ignored, and a number and a string
888 with that number are the same argument. C<undef> is an argument too, and no LIVR 2.5 rule takes it:
889 C<< { boolean => undef } >> dies, like C<< { boolean => [undef] } >>. The LIVR 2.0
890 rules and custom rules get C<undef> as an argument, as before, and
891 C<< { iso_date => undef } >> stays C<iso_date>, as LIVR 2.0 ignored its arguments.
892  
893 They compare and check the string form of a value: a boolean, such as
894 C<JSON::PP::true>, is C<true> or C<false>. Format and checksum rules return
895 their own error code for a boolean, and C<FORMAT_ERROR> for a hash or a list.
896  
897 =over 4
898  
899 =item C<boolean>
900  
901 C<true>, C<false>, C<1>, C<0>, C<"1">, C<"0">, C<"true"> or C<"false">. The
902 output is C<JSON::PP::true> or C<JSON::PP::false>.
903 Errors: C<NOT_BOOLEAN>, C<FORMAT_ERROR>.
904  
905 =item C<< { not_one_of => [ @values ] } >>
906  
907 The value is none of C<@values>.
908 Errors: C<NOT_ALLOWED_VALUE>, C<FORMAT_ERROR>.
909  
910 =item C<< { max_decimals => $count } >>
911  
912 A number with at most C<$count> digits after the decimal point; trailing zeros
913 do not count. The output is a number.
914 Errors: C<TOO_MANY_DECIMALS>, C<NOT_NUMBER>, C<FORMAT_ERROR>.
915  
916 =item C<digits>
917  
918 ASCII digits, the leading zeros are kept: the output is a string.
919 Errors: C<NOT_DIGITS>, C<FORMAT_ERROR>.
920  
921 =item C<< { starts_with => [ @strings ] } >>, C<< { ends_with => [ @strings ] } >>, C<< { contains => [ @strings ] } >>
922  
923 The value starts with, ends with or contains one of C<@strings>.
924 Errors: C<WRONG_FORMAT>, C<FORMAT_ERROR>.
925  
926 =item C<iso_datetime>, C<< { iso_datetime => { min => $bound, max => $bound } } >>
927  
928 A date and a time with an offset, such as C<2026-10-29T10:00+02:00>. The output
929 is the time in UTC, C<2026-10-29T08:00:00.000Z>. A bound is a datetime, a date
930 (its start as C<min>, its end as C<max>) or C<today>, C<yesterday> and
931 C<tomorrow>.
932 Errors: C<WRONG_DATETIME>, C<DATETIME_TOO_EARLY>, C<DATETIME_TOO_LATE>, C<FORMAT_ERROR>.
933  
934 =item C<iso_time>, C<< { iso_time => { min => $time, max => $time } } >>
935  
936 C<HH:MM>, C<HH:MM:SS> or C<HH:MM:SS.fraction>. With C<min> greater than C<max>
937 the range goes over midnight.
938 Errors: C<WRONG_TIME>, C<TIME_TOO_EARLY>, C<TIME_TOO_LATE>, C<FORMAT_ERROR>.
939  
940 =item C<< { required_if => { $reference => $value, ... } } >>
941  
942 The field is required when all referenced fields have the given values, or one
943 of the values of a list. A reference is a field name or a path, such as
944 C<address/country>.
945 Error: C<REQUIRED>.
946  
947 =item C<< { when => [ $reference, $condition, $rules_if_true, $rules_if_false ] } >>, C<< { when => [ $reference, { $value => $rules, ... } ] } >>
948  
949 Validates the field with rules that depend on another field: on whether it
950 passes the C<$condition> rules, or on its value.
951  
952 vat_number => { when => [ 'type', { eq => 'company' }, [ 'required', 'string' ], { eq => '' } ] },
953  
954 Errors: C<NOT_ALLOWED_VALUE> and the errors of the rules.
955  
956 =item C<< { values => \@rules } >>, C<< { keys => \@rules } >>
957  
958 A hash with every value or every key validated with the rules. A wrong key gets
959 C<WRONG_KEY>.
960 Errors: C<WRONG_KEY>, C<FORMAT_ERROR> and the errors of the rules.
961  
962 =item C<any>
963  
964 Any value, the hashes and lists too, stays in the output unchanged.
965  
966 =item C<< { list_length => $length } >>, C<< { list_length => [ $min, $max ] } >>, C<< { list_length => { min => $min, max => $max } } >>
967  
968 A list with that number of items.
969 Errors: C<TOO_FEW_ITEMS>, C<TOO_MANY_ITEMS>, C<FORMAT_ERROR>.
970  
971 =item C<unique>, C<< { unique => [ @keys ] } >>
972  
973 A list without duplicates, or of hashes without duplicate values of C<@keys>.
974 Errors: C<NOT_UNIQUE_ITEMS>, C<FORMAT_ERROR>.
975  
976 =item C<< { split => $separator } >>
977  
978 A modifier: splits a string into a list, C<"1,2,3"> into C<["1", "2", "3"]>.
979 A number or a boolean is split in its string form, a list stays as it is.
980  
981 =item Formats
982  
983 C<uuid> (or C<< { uuid => [ 'v4', 'v7' ] } >>), C<ip> (or C<< { ip => 'v4' } >>,
984 C<< { ip => 'v6' } >>), C<cidr> (the same), C<hostname>, C<base64> (or
985 C<< { base64 => 'url' } >>), C<hex>, C<< { digest => [ 'md5', 'sha256' ] } >>
986 (also C<sha1>, C<sha384>, C<sha512>), C<mongo_id>, C<hex_color>, C<mac> (or
987 C<< { mac => 64 } >>), C<e164>, C<semver> and C<jwt>.
988 Errors: C<WRONG_UUID>, C<WRONG_IP>, C<WRONG_CIDR>, C<WRONG_HOSTNAME>,
989 C<WRONG_BASE64>, C<WRONG_HEX>, C<WRONG_DIGEST>, C<WRONG_MONGO_ID>,
990 C<WRONG_HEX_COLOR>, C<WRONG_MAC>, C<WRONG_E164>, C<WRONG_SEMVER>, C<WRONG_JWT>,
991 C<FORMAT_ERROR>.
992  
993 =item Checksums
994  
995 C<luhn>, C<credit_card> and C<iban>. The value is checked as it is: remove
996 spaces before, with C<< { remove => ' -' } >>.
997 Errors: C<WRONG_CHECKSUM>, C<WRONG_CREDIT_CARD_NUMBER>, C<WRONG_IBAN>, C<FORMAT_ERROR>.
998  
999 =back
1000  
1001 =head2 Testing rules with the current date
1002  
1003 The bounds C<today>, C<yesterday> and C<tomorrow> read the system time with
1004 C<time>. To fix it in tests, load L<Test::MockTime> before the first validator
1005 with such a bound is built:
1006  
1007 use Test::MockTime qw(set_fixed_time);
1008 use Validator::LIVR;
1009  
1010 set_fixed_time('2026-10-18T12:00:00Z', '%Y-%m-%dT%H:%M:%SZ');
1011  
1012 =head1 CLASS METHODS
1013  
1014 =head2 new
1015  
1016 my $validator = Validator::LIVR->new( \%rules );
1017 my $validator = Validator::LIVR->new( \%rules, $is_auto_trim );
1018  
1019 Creates a validator. With a true C<$is_auto_trim>, it trims all strings of the
1020 input, the nested ones too, before validation, so the output is trimmed as
1021 well. When C<$is_auto_trim> is C<undef>, the value set with
1022 L</default_auto_trim> is used.
1023  
1024 =head2 register_default_rules
1025  
1026 Validator::LIVR->register_default_rules(
1027 my_rule => \&my_rule_builder,
1028 other_rule => \&other_rule_builder,
1029 );
1030  
1031 Adds rules or replaces existing ones for all validators created after the call.
1032 See L</WRITING RULES IN PERL> for how to write a rule builder.
1033  
1034 =head2 register_aliased_default_rule
1035  
1036 Validator::LIVR->register_aliased_default_rule({
1037 name => 'valid_address',
1038 rules => { nested_object => {
1039 country => 'required',
1040 city => 'required',
1041 zip => 'positive_integer',
1042 } },
1043 error => 'WRONG_ADDRESS', # optional
1044 });
1045  
1046 Adds an alias for all validators created after the call. Then the alias works
1047 as any other rule:
1048  
1049 { address => [ 'required', 'valid_address' ] }
1050  
1051 Without C<error>, the alias returns the error of its rules.
1052  
1053 =head2 get_default_rules
1054  
1055 my $rule_builders = Validator::LIVR->get_default_rules();
1056  
1057 Returns a hashref that maps rule names to the rule builders that new validators
1058 get.
1059  
1060 =head2 default_auto_trim
1061  
1062 Validator::LIVR->default_auto_trim(1);
1063  
1064 Turns auto trim on or off for validators created after the call. See L</new>.
1065  
1066 =head1 OBJECT METHODS
1067  
1068 =head2 validate
1069  
1070 my $valid_data = $validator->validate( \%input );
1071  
1072 Returns a hashref with the valid data: only the fields that have rules, with
1073 the changes made by modifiers. On errors returns C<undef>, and L</get_errors>
1074 returns the errors.
1075  
1076 =head2 get_errors
1077  
1078 my $errors = $validator->get_errors();
1079  
1080 Returns the errors of the last L</validate> call, or C<undef> when it passed.
1081 The errors are a hashref that maps fields to error codes, with nested errors for
1082 metarules:
1083  
1084 {
1085 email => 'WRONG_EMAIL',
1086 address => { zip => 'NOT_POSITIVE_INTEGER' },
1087 products => [ undef, { quantity => 'TOO_LOW' } ],
1088 }
1089  
1090 When the input is not a hashref, the errors are the string C<FORMAT_ERROR>.
1091  
1092 =head2 register_rules
1093  
1094 $validator->register_rules( my_rule => \&my_rule_builder, ... );
1095  
1096 Adds rules or replaces existing ones, as L</register_default_rules> does, for
1097 this validator only. Returns the validator, so the call can be chained.
1098  
1099 =head2 register_aliased_rule
1100  
1101 $validator->register_aliased_rule({
1102 name => 'strong_password',
1103 rules => { min_length => 12 },
1104 error => 'WEAK_PASSWORD',
1105 });
1106  
1107 Adds an alias, as L</register_aliased_default_rule> does, for this validator
1108 only. Returns the validator.
1109  
1110 =head2 get_rules
1111  
1112 my $rule_builders = $validator->get_rules();
1113  
1114 Returns a hashref that maps rule names to the rule builders of this validator.
1115  
1116 =head2 prepare
1117  
1118 my $validator = Validator::LIVR->new($rules)->prepare();
1119  
1120 Builds the validators of all rules and returns the validator. L</validate> does
1121 it on the first call, so you need C<prepare> only to find mistakes early. It
1122 dies with C<Rule [name] not registered> when a rule is unknown, and with
1123 C<Rule [name1, name2] should have one name> when a hash has several rules.
1124 Register your rules before C<prepare> or the first L</validate>.
1125  
1126 =head1 WRITING RULES IN PERL
1127  
1128 A rule is a builder: a sub that gets the arguments of the rule and returns a
1129 validator sub. The builder is called once, when the validator is prepared. The
1130 validator sub is called for every value.
1131  
1132 Here is how C<max_number> could be written:
1133  
1134 use Scalar::Util qw(looks_like_number);
1135  
1136 Validator::LIVR->register_default_rules( max_number => sub {
1137 my ( $max_number, $rule_builders ) = @_;
1138  
1139 return sub {
1140 my ( $value, $all_values, $output_ref ) = @_;
1141  
1142 # Empty values are the job of "required"
1143 return if !defined($value) || $value eq '';
1144  
1145 return 'FORMAT_ERROR' if ref($value);
1146 return 'NOT_NUMBER' if !looks_like_number($value);
1147 return 'TOO_HIGH' if $value > $max_number;
1148 return;
1149 };
1150 });
1151  
1152 The builder gets the arguments of the rule, then a hashref of all rule builders
1153 of the validator, which the builder must not change:
1154  
1155 'my_rule' # ( $rule_builders )
1156 { my_rule => $arg } # ( $arg, $rule_builders )
1157 { my_rule => [ $arg ] } # ( $arg, $rule_builders )
1158 { my_rule => [ $arg1, $arg2 ] } # ( $arg1, $arg2, $rule_builders )
1159  
1160 The validator sub gets:
1161  
1162 =over 4
1163  
1164 =item C<$value>
1165  
1166 The value of the field, as the previous rules of the field left it.
1167  
1168 =item C<$all_values>
1169  
1170 The hash that has the field, to compare it with other fields, as
1171 C<equal_to_field> does. Inside C<or> and aliases, it is the hash of the field
1172 that uses them. Inside C<list_of>, C<values> and C<keys>, it is empty.
1173  
1174 =item C<$output_ref>
1175  
1176 A reference to the output value. Assign to it to change the value, as
1177 modifiers do.
1178  
1179 =back
1180  
1181 It returns nothing when the value is valid, and an error code when it is not.
1182  
1183 A modifier sets the output and returns nothing:
1184  
1185 Validator::LIVR->register_default_rules( to_ucfirst => sub {
1186 return sub {
1187 my ( $value, undef, $output_ref ) = @_;
1188 return if !defined($value) || ref($value) || $value eq '';
1189  
1190 $$output_ref = ucfirst($value);
1191 return;
1192 };
1193 });
1194  
1195 With C<$rule_builders>, a rule can validate nested data with the same rules,
1196 as metarules do:
1197  
1198 my $validator = Validator::LIVR->new($rules)->register_rules(%$rule_builders)->prepare();
1199  
1200 The built-in rules are short and make good examples:
1201 L<Validator::LIVR::Rules::Common>, L<Validator::LIVR::Rules::String>,
1202 L<Validator::LIVR::Rules::Numeric>, L<Validator::LIVR::Rules::Special>,
1203 L<Validator::LIVR::Rules::Meta> and L<Validator::LIVR::Rules::Modifiers>. The
1204 LIVR 2.5 rules are in L<Validator::LIVR::Rules::Types>,
1205 L<Validator::LIVR::Rules::DateTime>, L<Validator::LIVR::Rules::Conditional>,
1206 L<Validator::LIVR::Rules::Collection> and L<Validator::LIVR::Rules::Format>.
1207  
1208 =head1 SEE ALSO
1209  
1210 =over 4
1211  
1212 =item * L<The LIVR specification|https://livr-spec.org>, with all rules,
1213 L<aliases|https://livr-spec.org/rules-aliasing.html> and a
1214 L<playground|https://livr-spec.org/playground.html>.
1215  
1216 =item * L<The LIVR repository|https://github.com/koorchik/LIVR>, with the
1217 specification and its test suite.
1218  
1219 =item * L<LIVR implementations|https://livr-spec.org/introduction/implementations.html>
1220 in other languages.
1221  
1222 =back
1223  
1224 =head1 BUGS AND SUPPORT
1225  
1226 Please report bugs and ideas in
1227 L<GitHub Issues|https://github.com/koorchik/Validator-LIVR/issues>. The source
1228 is at L<https://github.com/koorchik/Validator-LIVR>.
1229  
1230 You can read this documentation with C<perldoc Validator::LIVR>, or on
1231 L<MetaCPAN|https://metacpan.org/pod/Validator::LIVR>.
1232  
1233 =head1 AUTHOR
1234  
1235 Viktor Turskyi, C<< <koorchik at cpan.org> >>
1236  
1237 =head1 LICENSE AND COPYRIGHT
1238  
1239 Copyright 2012-2026 Viktor Turskyi.
1240  
1241 This program is free software; you can redistribute it and/or modify it
1242 under the terms of the Artistic License (2.0). You may obtain a
1243 copy of the full license at:
1244  
1245 L<https://www.perlfoundation.org/artistic-license-20.html>
1246  
1247 Any use, modification, and distribution of the Standard or Modified
1248 Versions is governed by this Artistic License. By using, modifying or
1249 distributing the Package, you accept this license. Do not use, modify,
1250 or distribute the Package, if you do not accept this license.
1251  
1252 If your Modified Version has been derived from a Modified Version made
1253 by someone other than you, you are nevertheless required to ensure that
1254 your Modified Version complies with the requirements of this license.
1255  
1256 This license does not grant you the right to use any trademark, service
1257 mark, tradename, or logo of the Copyright Holder.
1258  
1259 This license includes the non-exclusive, worldwide, free-of-charge
1260 patent license to make, have made, use, offer to sell, sell, import and
1261 otherwise transfer the Package with respect to any patent claims
1262 licensable by the Copyright Holder that are necessarily infringed by the
1263 Package. If you institute patent litigation (including a cross-claim or
1264 counterclaim) against any party alleging that the Package constitutes
1265 direct or contributory patent infringement, then this Artistic License
1266 to you shall terminate on the date that such litigation is filed.
1267  
1268 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
1269 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
1270 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
1271 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
1272 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
1273 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
1274 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
1275 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1276  
1277 =cut
« LIVR/Rules/Meta.pm ↑ Summary LIVR/Rules/Format.pm »