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 next if ($l =~ m/^#/);
78 my @d = split(/\s+/, $l);
80 my $fld = shift @d || $log->logdie("need field name in line $curr_line: $l");
90 $log->debug("current validation rules: ", Dumper($v));
94 $self ? return $self : return undef;
97 =head2 validate_errors
99 Validate record and return errors
101 my @errors = $validate->validate_errors( $rec );
105 sub validate_errors {
108 my $log = $self->_get_logger();
110 my $rec = shift || $log->logdie("validate_errors need record");
112 $log->logdie("rec isn't HASH") unless (ref($rec) eq 'HASH');
113 $log->logdie("can't find validation rules") unless (my $r = $self->{rules});
117 $log->debug("rec = ", sub { Dumper($rec) }, "keys = ", keys %{ $rec });
119 foreach my $f (keys %{ $rec }) {
121 next if (!defined($f) || $f eq '');
123 if (! defined($r->{$f})) {
124 push @errors, "field '$f' shouldn't exists";
128 if (ref($rec->{$f}) ne 'ARRAY') {
129 push @errors, "field '$f' isn't repetable, probably bug in parsing input data";
133 foreach my $v (@{ $rec->{$f} }) {
134 # can we have subfields?
135 if (ref($r->{$f}) eq 'ARRAY') {
136 # are values hashes? (has subfields)
137 if (ref($v) ne 'HASH') {
138 push @errors, "$f has value without subfields: $v";
141 foreach my $sf (keys %{ $v }) {
143 if (! first { $_ eq $sf } @{ $r->{$f} }) {
144 push @errors, "$f has unknown subfield: $sf";
148 } elsif (ref($v) eq 'HASH') {
149 push @errors, "$f has subfields which is not valid";
154 #$log->logcluck("return from this function is ARRAY") unless wantarray;
156 $log->debug("errors: ", join(", ", @errors)) if (@errors);
163 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>
165 =head1 COPYRIGHT & LICENSE
167 Copyright 2006 Dobrica Pavlinusic, All Rights Reserved.
169 This program is free software; you can redistribute it and/or modify it
170 under the same terms as Perl itself.
174 1; # End of WebPAC::Validate