File: Simple.pm

package info (click to toggle)
libcatmandu-perl 0.9206-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,768 kB
  • ctags: 512
  • sloc: perl: 7,798; makefile: 34
file content (83 lines) | stat: -rw-r--r-- 1,776 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
83
package Catmandu::Validator::Simple;

use Catmandu::Sane;
use Moo;

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;
}

=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 METHODS

=head2 new(handler => \&callback, %options)

The I<callback> function should take $hashref to a data record 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.

The constructor also accepts the common options for L<Catmandu::Validator>.

=head2 is_valid(...)

=head2 validate(...)

=head2 last_errors(...)

=head2 valid_count()

=head2 invalid_count()

These are methods are inherited from L<Catmandu::Validator>.

=head1 SEE ALSO

L<Catmandu::Validator>

=cut

1;