1 package WebPAC::Validate;
8 use base 'WebPAC::Common';
10 use List::Util qw/first/;
15 WebPAC::Validate - provide simple validation for records
23 our $VERSION = '0.01';
27 This module provide a simple way to validate your file against a simple
28 configuration file in following format:
30 # field 10 doesn't have any subfields
34 # field 200 have valid subfields a-g
36 # field 205 can have only subfield a
38 # while 210 can have a c or d
45 Create new validation object
47 my $validate = new WebPAC::Validate(
48 path => '/path/to/input/validate_file',
58 my $log = $self->_get_logger();
60 foreach my $p (qw/path/) {
61 $log->logconfess("need $p") unless ($self->{$p});
64 my $v_file = read_file( $self->{path} ) ||
65 $log->logdie("can't open validate path $self->{path}: $!");
70 foreach my $l (split(/[\n\r]+/, $v_file)) {
73 # skip comments and whitespaces
74 next if ($l =~ /^#/ || $l =~ /^\s*$/);
79 my @d = split(/\s+/, $l);
83 $log->logdie("need field name in line $curr_line: $l") unless (defined($fld));
93 $log->debug("current validation rules: ", Dumper($v));
97 $log->info("validation uses rules from $self->{path}");
99 $self ? return $self : return undef;
102 =head2 validate_errors
104 Validate record and return errors
106 my @errors = $validate->validate_errors( $rec );
110 sub validate_errors {
113 my $log = $self->_get_logger();
115 my $rec = shift || $log->logdie("validate_errors need record");
117 $log->logdie("rec isn't HASH") unless (ref($rec) eq 'HASH');
118 $log->logdie("can't find validation rules") unless (my $r = $self->{rules});
122 $log->debug("rec = ", sub { Dumper($rec) }, "keys = ", keys %{ $rec });
124 foreach my $f (keys %{ $rec }) {
126 next if (!defined($f) || $f eq '' || $f eq '000');
128 if (! defined($r->{$f})) {
129 push @errors, "field '$f' shouldn't exists";
133 if (ref($rec->{$f}) ne 'ARRAY') {
134 push @errors, "field '$f' isn't repetable, probably bug in parsing input data";
138 foreach my $v (@{ $rec->{$f} }) {
139 # can we have subfields?
140 if (ref($r->{$f}) eq 'ARRAY') {
141 # are values hashes? (has subfields)
142 if (ref($v) ne 'HASH') {
143 push @errors, "$f has value without subfields: $v";
146 foreach my $sf (keys %{ $v }) {
148 if (! first { $_ eq $sf } @{ $r->{$f} }) {
149 push @errors, "$f has unknown subfield: $sf";
153 } elsif (ref($v) eq 'HASH') {
154 push @errors, "$f has subfields which is not valid";
159 #$log->logcluck("return from this function is ARRAY") unless wantarray;
161 $log->debug("errors: ", join(", ", @errors)) if (@errors);
168 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>
170 =head1 COPYRIGHT & LICENSE
172 Copyright 2006 Dobrica Pavlinusic, All Rights Reserved.
174 This program is free software; you can redistribute it and/or modify it
175 under the same terms as Perl itself.
179 1; # End of WebPAC::Validate