File: Simple.pm

package info (click to toggle)
libcatmandu-perl 1.2020-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,552 kB
  • sloc: perl: 16,933; makefile: 24; sh: 1
file content (82 lines) | stat: -rw-r--r-- 1,633 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package Catmandu::Validator::Simple;

use Catmandu::Sane;

our $VERSION = '1.2020';

use Moo;
use namespace::clean;

with 'Catmandu::Validator';

has handler => (
    is       => 'rw',
    required => 1,
    isa      => sub {
        Catmandu::BadArg->throw("handler should be a CODE reference")
            unless ref $_[0] eq 'CODE';
    },
);

sub validate_data {
    my ($self, $data) = @_;

    my $error_messages = &{$self->handler}($data);
    $error_messages = [$error_messages]
        unless !$error_messages || ref $error_messages eq 'ARRAY';
    return $error_messages;
}

1;

__END__

=pod

=head1 NAME

Catmandu::Validator::Simple - Simple Validator for Catmandu

=head1 SYNOPSIS

    use Catmandu::Validator::Simple;

    my $validator = Catmandu::Validator::Simple->new(
        handler => sub {
            $data = shift;
            return "error" unless $data->{title} =~ m/good title/;
            return;
        }
    );

    if ( $validator->is_valid($hashref) ) {
        save_record_in_database($hashref);
    } else {
        reject_form($validator->last_errors);
    }


=head1 DESCRIPTION

Catmandu::Validator::Simple can be used for doing simple data validation in
Catmandu.

=head1 CONFIGURATION

=over

=item handler

A function that takes a hash reference item as argument. Should return undef if
the record passes validation otherwise return an error or an arrayref of
errors.  Each error can be either a simple message string or a hashref to a
more detailed error information.

=back

=head1 SEE ALSO

See L<Catmandu::Validator> for inherited methods, common configuration options,
and usage.

=cut