Apache-Voodoo
view release on metacpan or search on metacpan
lib/Apache/Voodoo/Validate.pm view on Meta::CPAN
package Apache::Voodoo::Validate;
$VERSION = "3.0200";
use strict;
use warnings;
use Apache::Voodoo::Exception;
sub new {
my $class = shift;
my $config = shift || {};
my $self = {};
bless $self, $class;
$self->{'ef'} = sub {
my ($f,$t,$e) = @_;
$e->{$t.'_'.$f} = 1;
};
$self->_configure($config);
return $self;
}
sub set_valid_callback {
my $self = shift;
#my $context = shift;
my $sub_ref = shift;
#unless (defined($context)) {
# Apache::Vodooo::Exception::RunTime->throw("add_callback requires a context name as the first parameter");
#}
unless (ref($sub_ref) eq "CODE") {
Apache::Vodooo::Exception::RunTime::BadConfig->throw("add_callback requires a subroutine reference as the second paramter");
}
#push(@{$self->{'callbacks'}->{$context}},$sub_ref);
$self->{'vc'} = $sub_ref;
}
sub set_error_formatter {
my $self = shift;
my $sub_ref = shift;
if (ref($sub_ref) eq "CODE") {
$self->{'ef'} = $sub_ref;
}
}
sub required { return map { $_->name } grep { $_->required } @{$_[0]->{fields}} };
sub unique { return map { $_->name } grep { $_->unique } @{$_[0]->{fields}} };
sub multiple { return map { $_->name } grep { $_->multiple } @{$_[0]->{fields}} };
sub fields {
my $self = shift;
my $type = shift;
if ($type) {
return grep { $_->type eq $type } @{$self->{fields}};
}
else {
return @{$self->{fields}};
}
}
sub validate {
my $self = shift;
my $p = shift;
my $values = {};
my $errors = {};
foreach my $field ($self->fields) {
my $good;
my $missing = 1;
my $bad = 0;
foreach ($self->_param($p,$field)) {
next unless defined ($_);
# call the validation routine for each value
my ($v,@b) = $field->valid($_);
if (defined($b[0])) {
# bad one, we're outta here.
$bad = 1;
foreach (@b) {
$self->{'ef'}->($field->{'name'},$_,$errors);
}
last;
}
elsif (defined($field->valid_sub)) {
# there's a validation subroutine, call it
my $r = $field->valid_sub()->($v);
if (defined($r) && $r == 1) {
push(@{$good},$v);
$missing = 0;
( run in 0.852 second using v1.01-cache-2.11-cpan-39bf76dae61 )