Merge branch 'b-3.6.1' of ../kivitendo-erp_20220811
[kivitendo-erp.git] / SL / DB / Helper / VATIDNrValidation.pm
1 package SL::DB::Helper::VATIDNrValidation;
2
3 use strict;
4
5 use Carp;
6 use SL::Locale::String qw(t8);
7 use SL::VATIDNr;
8
9 my $_validator;
10
11 sub _validate {
12   my ($self, $attribute) = @_;
13
14   my $number = SL::VATIDNr->clean($self->$attribute);
15
16   return () unless length($number);
17   return () if     SL::VATIDNr->validate($number);
18   return ($::locale->text("The VAT ID number '#1' is invalid.", $self->$attribute));
19 }
20
21 sub import {
22   my ($package, @attributes) = @_;
23
24   my $caller_package         = caller;
25   @attributes                = qw(ustid) unless @attributes;
26
27   no strict 'refs';
28
29   *{ $caller_package . '::validate_vat_id_numbers' } = sub {
30     my ($self) = @_;
31
32     return map { SL::DB::Helper::VATIDNrValidation::_validate($self, $_) } @attributes;
33   };
34 }
35
36 1;
37
38 __END__
39
40 =pod
41
42 =encoding utf8
43
44 =head1 NAME
45
46 SL::DB::Helper::VATIDNrValidation - Mixin for validating VAT ID number attributes
47
48 =head1 SYNOPSIS
49
50   package SL::DB::SomeObject;
51   use SL::DB::Helper::VATIDNrValidation [ ATTRIBUTES ];
52
53   sub validate {
54     my ($self) = @_;
55
56     my @errors;
57     …
58     push @errors, $self->validate_vat_id_numbers;
59
60     return @errors;
61   }
62
63 This mixin provides a function C<validate_vat_id_numbers> that returns
64 a list of error messages, one for each attribute that fails the VAT ID
65 number validation. If all attributes are valid or empty then an empty
66 list is returned.
67
68 The names of attributes to check can be given as an import list to the
69 mixin package. If no attributes are given the single attribute C<ustid>
70 is used.
71
72 =head1 FUNCTIONS
73
74 =over 4
75
76 =item C<validate_vat_id_numbers>
77
78 This function iterates over all configured attributes and validates
79 their content according to how VAT ID numbers are supposed to be
80 formatted in the European Union (or the enterprise identification
81 numbers in Switzerland). An attribute that is undefined, empty or
82 consists solely of whitespace is considered valid, too.
83
84 The function returns a list of human-readable error messages suitable
85 for use in a general C<validate> function (see SYNOPSIS). For each
86 attribute failing the check the list will include one error message.
87
88 If all attributes are valid then an empty list is returned.
89
90 =back
91
92 =head1 BUGS
93
94 Nothing here yet.
95
96 =head1 AUTHOR
97
98 Moritz Bunkus E<lt>m.bunkus@linet-services.deE<gt>
99
100 =cut